For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > April 2005 > Sort array by value length ?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Sort array by value length ?
Michael Gale

2005-04-22, 8:55 pm

Hello,

I have an array of names and would like to sort the array by the length
of the name but am having difficulty.

Any suggestions ?

I tried creating two arrays, one with the names and another with the
length values, then sorting the length values but found it difficult to
print them out.

Michael
Ankur Gupta

2005-04-22, 8:55 pm

> Hello,

Hi,

> I have an array of names and would like to sort the array by
> the length of the name but am having difficulty.
>
> Any suggestions ?


if you want to sort in ascending order
@sorted = sort { length($a) <=> length($b) } @unsorted;

or if in descending order
@sorted = sort { length($b) <=> length($a) } @unsorted;

perldoc -f sort will give you many useful examples.

--Ankur


John W. Krahn

2005-04-22, 8:55 pm

Michael Gale wrote:
> Hello,


Hello,

> I have an array of names and would like to sort the array by the length
> of the name but am having difficulty.
>
> Any suggestions ?


$ perl -le'
my @names = qw/ zero one two three four five six seven eight nine /;
print "@names";

my @sorted_names = sort @names;
print "@sorted_names";

my @by_length = sort { length $a <=> length $b } @names;
print "@by_length";
'
zero one two three four five six seven eight nine
eight five four nine one seven six three two zero
one two six zero four five nine three seven eight


> I tried creating two arrays, one with the names and another with the
> length values, then sorting the length values but found it difficult to
> print them out.


If you want to keep the by-length index in another array:

$ perl -le'
my @names = qw/ zero one two three four five six seven eight nine /;
print "@names";

my @sorted_names = sort @names;
print "@sorted_names";

my @index_by_length = sort { length $names[$a] <=> length $names[$b] } 0 ..
$#names;
print "@names[@index_by_length]";
'
zero one two three four five six seven eight nine
eight five four nine one seven six three two zero
one two six zero four five nine three seven eight




John
--
use Perl;
program
fulfillment
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com