Perl sort blocks and the Schwartzian transform

Perl's sort without a block sorts as strings, so 10 comes before 9. A sort block receives the two elements to compare in the special variables $a and $b and returns a negative number, zero, or a positive number. <=> compares numbers and cmp compares strings. The keyword or chains comparisons, so a second key is used only when the first is equal. reverse flips a sorted list.

Perl
use strict;
use warnings;

my @nums = (10, 9, 1, 25);
print join(" ", sort @nums), "\n";
print join(" ", sort { $a <=> $b } @nums), "\n";
print join(" ", reverse sort { $a <=> $b } @nums), "\n";

my %age = (Ada => 30, Bo => 25, Cy => 30, Di => 25);
my @by_age = sort { $age{$b} <=> $age{$a} or $a cmp $b } keys %age;
print "@by_age\n";

my @words = qw(pear fig apple kiwi);
my @by_length =
    map  { $_->[1] }
    sort { $a->[0] <=> $b->[0] or $a->[1] cmp $b->[1] }
    map  { [length($_), $_] } @words;
print "@by_length\n";
Read the full lesson