CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Frequently Asked Questions:
How do I sort an array by (anything)?

 



Jasmine
Administrator

Jan 19, 2001, 3:19 PM

Post #1 of 1 (1411 views)
How do I sort an array by (anything)? Can't Post

(From the Perl FAQ)

How do I sort an array by (anything)?

Supply a comparison function to sort() (described in sort):

Code
    @list = sort { $a <=> $b } @list;

The default sort function is cmp, string comparison, which would sort (1, 2, 10) into (1, 10, 2). <=>, used above, is the numerical comparison operator.

If you have a complicated function needed to pull out the part you want to sort on, then don't do it inside the sort function. Pull it out first, because the sort BLOCK can be called many times for the same element. Here's an example of how to pull out the first word after the first number on each item, and then sort those words case-insensitively.

Code
    @idx = (); 
for (@data) {
($item) = /\d+\s*(\S+)/;
push @idx, uc($item);
}
@sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];

Which could also be written this way, using a trick that's come to be known as the Schwartzian Transform:

Code
    @sorted = map  { $_->[0] } 
sort { $a->[1] cmp $b->[1] }
map { [ $_, uc((/\d+\s*(\S+)/ )[0] ] } @data;

If you need to sort on several fields, the following paradigm is useful.

Code
    @sorted = sort { field1($a) <=> field1($b) || 
field2($a) cmp field2($b) ||
field3($a) cmp field3($b)
} @data;

This can be conveniently combined with precalculation of keys as given above.

See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for more about this approach.



 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives