FAQ 4.52 How do I sort an array by (anything)?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.


4.52: How do I sort an array by (anything)?

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

        @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

    See the sort article in the "Far More Than You Ever Wanted To Know"
    collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz for more
    about this approach.

    See also the question below on sorting hashes.


Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.


    Copyright (c) 1997-2002 Tom Christiansen and Nathan
    Torkington, and other contributors as noted. All rights

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.

Site Timeline