Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister


by gods
on Aug 24, 1999 at 22:43 UTC ( #344=perlfunc: print w/ replies, xml ) Need Help??


See the current Perl documentation for sort.


sort - sort a list of values



sort LIST


In the interests of efficiency the normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine not via @_ but as the package global variables $a and $b (see example below). They are passed by reference, so don't modify $a and $b. And don't try to declare them as lexicals either.

You also cannot exit out of the sort block or subroutine using any of the loop control operators described in the perlsyn manpage or with goto().

When use locale is in effect, sort LIST sorts LIST according to the current collation locale. See the perllocale manpage.


    # sort lexically
    @articles = sort @files;

    # same thing, but with explicit sort routine

    # now case-insensitively

    # same thing in reversed order

    # sort numerically ascending

    # sort numerically descending

    # sort using explicit subroutine name
    sub byage {
    @sortedclass = sort byage @class;

    # this sorts the %age hash by value instead of key
    # using an in-line function

    sub backwards { $b cmp $a; }
    print sort @harry;
            # prints AbelCaincatdogx
    print sort backwards @harry;
            # prints xdogcatCainAbel
    print sort @george, 'to', @harry;
            # prints AbelAxedCainPunishedcatchaseddoggonetoxyz

    # inefficiently sort by descending numeric compare using
    # the first integer after the first = sign, or the
    # whole record case-insensitively otherwise

    @new = sort {
                    uc($a)  cmp  uc($b)
    } @old;

    # same thing, but much more efficiently;
    # we'll build auxiliary indices instead
    # for speed
    @nums = @caps = ();
    for (@old) {
        push @caps, uc($_);

    @new = @old[ sort {
                       } 0..$#old

    # same thing using a Schwartzian Transform (no temps)

If you're using strict, you MUST NOT declare $a and $b as lexicals. They are package globals. That means if you're in the main package, it's

    @articles = sort {$main::b <=> $main::a} @files;

or just

    @articles = sort {$::b <=> $::a} @files;

but if you're in the FooPack package, it's



Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2014-12-27 14:22 GMT
Find Nodes?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?

    Results (177 votes), past polls