Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

How do I sort an array by (anything)?

by faq_monk (Initiate)
on Oct 08, 1999 at 00:20 UTC ( #619=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at

Here is our local, out-dated (pre-5.6) version:

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

    @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.

    @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:

    @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.

    @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 for more about this approach.

See also the question below on sorting hashes.

Log In?

What's my password?
Create A New User
[Spenser]: yes, I have mysql client libs installed.
[choroba]: You can also try DBD::MariaDB instead of MySQL
[choroba]: it's not on CPAN yet, unfortunately, so you have to install manually from github
[Spenser]: Thanks. I tried DBD::MariaDB just now. It can't find that module.
[Spenser]: oh, I'll check github

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2018-03-17 12:54 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (224 votes). Check out past polls.