sort SUBNAME LIST
sort BLOCK LIST
sort LIST
Sorts the LIST and returns the sorted list value. Nonexistent values
of arrays are stripped out. 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 array are
to be ordered. (The <=> and cmp operators are extremely useful in such
routines.) SUBNAME may be a scalar variable name, in which case the
value provides the name of the subroutine to use. In place of a
SUBNAME, you can provide a BLOCK as an anonymous, in™line sort
subroutine.
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 $a and $b (see example below).
They are passed by reference, so don't modify $a and $b.
Examples:
@articles = sort @files;
@articles = sort {$a cmp $b} @files;
@articles = sort {$b cmp $a} @files;
@articles = sort {$a <=> $b} @files;
@articles = sort {$b <=> $a} @files;
sub byage {
$age{$a} <=> $age{$b}; # presuming integers
}
@sortedclass = sort byage @class;
sub backwards { $b cmp $a; }
@harry = ('dog','cat','x','Cain','Abel');
@george = ('gone','chased','yz','Punished','Axed');
print sort @harry;
print sort backwards @harry;
print sort @george, 'to', @harry;
|
|
|