Perl version

Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

sort

Perl 5 version 26.1 documentation
Recently read

sort

  • sort SUBNAME LIST

  • sort BLOCK LIST
  • sort LIST

    In list context, this sorts the LIST and returns the sorted list value. In scalar context, the behaviour of sort is undefined.

    If SUBNAME or BLOCK is omitted, sorts in standard string comparison order. If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than 0 , depending on how the elements of the list are to be ordered. (The <=> and cmp operators are extremely useful in such routines.) SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine.

    If the subroutine's prototype is ($$) , the elements to be compared are passed by reference in @_ , as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b (see example below).

    If the subroutine is an XSUB, the elements to be compared are pushed on to the stack, the way arguments are usually passed to XSUBs. $a and $b are not set.

    The values to be compared are always passed by reference and should not be modified.

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

    When use locale (but not use locale ':not_characters' ) is in effect, sort LIST sorts LIST according to the current collation locale. See perllocale.

    sort returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by sort (for example, in a foreach , map or grep) actually modifies the element in the original list. This is usually something to be avoided when writing clear code.

    Perl 5.6 and earlier used a quicksort algorithm to implement sort. That algorithm was not stable and could go quadratic. (A stable sort preserves the input order of elements that compare equal. Although quicksort's run time is O(NlogN) when averaged over all arrays of length N, the time can be O(N**2), quadratic behavior, for some inputs.) In 5.7, the quicksort implementation was replaced with a stable mergesort algorithm whose worst-case behavior is O(NlogN). But benchmarks indicated that for some inputs, on some platforms, the original quicksort was faster. 5.8 has a sort pragma for limited control of the sort. Its rather blunt control of the underlying algorithm may not persist into future Perls, but the ability to characterize the input or output in implementation independent ways quite probably will.

    Examples:

    1. # sort lexically
    2. my @articles = sort @files;
    3. # same thing, but with explicit sort routine
    4. my @articles = sort {$a cmp $b} @files;
    5. # now case-insensitively
    6. my @articles = sort {fc($a) cmp fc($b)} @files;
    7. # same thing in reversed order
    8. my @articles = sort {$b cmp $a} @files;
    9. # sort numerically ascending
    10. my @articles = sort {$a <=> $b} @files;
    11. # sort numerically descending
    12. my @articles = sort {$b <=> $a} @files;
    13. # this sorts the %age hash by value instead of key
    14. # using an in-line function
    15. my @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
    16. # sort using explicit subroutine name
    17. sub byage {
    18. $age{$a} <=> $age{$b}; # presuming numeric
    19. }
    20. my @sortedclass = sort byage @class;
    21. sub backwards { $b cmp $a }
    22. my @harry = qw(dog cat x Cain Abel);
    23. my @george = qw(gone chased yz Punished Axed);
    24. print sort @harry;
    25. # prints AbelCaincatdogx
    26. print sort backwards @harry;
    27. # prints xdogcatCainAbel
    28. print sort @george, 'to', @harry;
    29. # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
    30. # inefficiently sort by descending numeric compare using
    31. # the first integer after the first = sign, or the
    32. # whole record case-insensitively otherwise
    33. my @new = sort {
    34. ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
    35. ||
    36. fc($a) cmp fc($b)
    37. } @old;
    38. # same thing, but much more efficiently;
    39. # we'll build auxiliary indices instead
    40. # for speed
    41. my (@nums, @caps);
    42. for (@old) {
    43. push @nums, ( /=(\d+)/ ? $1 : undef );
    44. push @caps, fc($_);
    45. }
    46. my @new = @old[ sort {
    47. $nums[$b] <=> $nums[$a]
    48. ||
    49. $caps[$a] cmp $caps[$b]
    50. } 0..$#old
    51. ];
    52. # same thing, but without any temps
    53. my @new = map { $_->[0] }
    54. sort { $b->[1] <=> $a->[1]
    55. ||
    56. $a->[2] cmp $b->[2]
    57. } map { [$_, /=(\d+)/, fc($_)] } @old;
    58. # using a prototype allows you to use any comparison subroutine
    59. # as a sort subroutine (including other package's subroutines)
    60. package Other;
    61. sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are
    62. # not set here
    63. package main;
    64. my @new = sort Other::backwards @old;
    65. # guarantee stability, regardless of algorithm
    66. use sort 'stable';
    67. my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
    68. # force use of mergesort (not portable outside Perl 5.8)
    69. use sort '_mergesort'; # note discouraging _
    70. my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;

    Warning: syntactical care is required when sorting the list returned from a function. If you want to sort the list returned by the function call find_records(@key) , you can use:

    1. my @contact = sort { $a cmp $b } find_records @key;
    2. my @contact = sort +find_records(@key);
    3. my @contact = sort &find_records(@key);
    4. my @contact = sort(find_records(@key));

    If instead you want to sort the array @key with the comparison routine find_records() then you can use:

    1. my @contact = sort { find_records() } @key;
    2. my @contact = sort find_records(@key);
    3. my @contact = sort(find_records @key);
    4. my @contact = sort(find_records (@key));

    $a and $b are set as package globals in the package the sort() is called from. That means $main::a and $main::b (or $::a and $::b ) in the main package, $FooPack::a and $FooPack::b in the FooPack package, etc. If the sort block is in scope of a my or state declaration of $a and/or $b , you must spell out the full name of the variables in the sort block :

    1. package main;
    2. my $a = "C"; # DANGER, Will Robinson, DANGER !!!
    3. print sort { $a cmp $b } qw(A C E G B D F H);
    4. # WRONG
    5. sub badlexi { $a cmp $b }
    6. print sort badlexi qw(A C E G B D F H);
    7. # WRONG
    8. # the above prints BACFEDGH or some other incorrect ordering
    9. print sort { $::a cmp $::b } qw(A C E G B D F H);
    10. # OK
    11. print sort { our $a cmp our $b } qw(A C E G B D F H);
    12. # also OK
    13. print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H);
    14. # also OK
    15. sub lexi { our $a cmp our $b }
    16. print sort lexi qw(A C E G B D F H);
    17. # also OK
    18. # the above print ABCDEFGH

    With proper care you may mix package and my (or state) $a and/or $b :

    1. my $a = {
    2. tiny => -2,
    3. small => -1,
    4. normal => 0,
    5. big => 1,
    6. huge => 2
    7. };
    8. say sort { $a->{our $a} <=> $a->{our $b} }
    9. qw{ huge normal tiny small big};
    10. # prints tinysmallnormalbighuge

    $a and $b are implicitely local to the sort() execution and regain their former values upon completing the sort.

    Sort subroutines written using $a and $b are bound to their calling package. It is possible, but of limited interest, to define them in a different package, since the subroutine must still refer to the calling package's $a and $b :

    1. package Foo;
    2. sub lexi { $Bar::a cmp $Bar::b }
    3. package Bar;
    4. ... sort Foo::lexi ...

    Use the prototyped versions (see above) for a more generic alternative.

    The comparison function is required to behave. If it returns inconsistent results (sometimes saying $x[1] is less than $x[2] and sometimes saying the opposite, for example) the results are not well-defined.

    Because <=> returns undef when either operand is NaN (not-a-number), be careful when sorting with a comparison function like $a <=> $b any lists that might contain a NaN . The following example takes advantage that NaN != NaN to eliminate any NaN s from the input list.

    1. my @result = sort { $a <=> $b } grep { $_ == $_ } @input;