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 and BLOCK are omitted, "sort"s in standard
string comparison order. Otherwise, SUBNAME or BLOCK
provides 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 should be the bareword name of a subroutine
or a simple scalar variable (unsubscripted) containing
either a subroutine name or a reference to a subroutine.
BLOCK is just an anonymous, in-line subroutine.
@names = sort @names;
@numbers = sort { $a <=> $b } @numbers;
sub hi2lo { $b <=> $a }
@numbers = sort hi2lo @numbers;
my $comparison = \&hi2lo;
@numbers = sort $comparison @numbers;
# Syntax error:
my %comparisons = get_compare_functions();
@numbers = sort $comparisons{hi2lo} @numbers;
# Not allowed ^^^^^^^
Beware when trying to sort the list returned from a
function call, as the obvious syntax does not do that:
@sorted = sort foo($x,$y); # same as:
@sorted = sort foo $x,$y; # or as:
my @list = ($x,$y);
@sorted = sort foo @list;
# Put just $x and $y into @sorted,
# using foo() to compare the values.
You must instead use something like:
@sorted = sort( foo($x,$y) );
@sorted = sort { $a cmp $b } foo $x,$y;
@sorted = sort +foo($x,$y);
@sorted = sort &foo($x,$y);
...describe more esoteric details...
...don't include more examples until later...
(so the examples of just syntax stand out)