Sorting
sort LIST returns a sorted copy of a list. By default it compares elements as strings. To sort any other way, give it a comparator block that compares two elements, $a and $b, and returns a negative number, zero or a positive number.
The comparator block
use strict;
use warnings;
my @nums = (42, 7, 108, 15, 7);
my @as_strings = sort @nums;
my @ascending = sort { $a <=> $b } @nums;
my @descending = sort { $b <=> $a } @nums;
print "Default (string): @as_strings\n";
print "Numeric: @ascending\n";
print "Descending: @descending\n";
my @words = qw(pear Apple fig banana);
print "By length: @{[ sort { length($a) <=> length($b) } @words ]}\n";
print "Reverse alpha: @{[ sort { $b cmp $a } @words ]}\n";Default (string): 108 15 42 7 7
Numeric: 7 7 15 42 108
Descending: 108 42 15 7 7
By length: fig pear Apple banana
Reverse alpha: pear fig banana Apple
$a and $b are special package variables set by sort; don't declare them with my. Use <=> for numbers and cmp for strings. Swapping $a and $b reverses the order.
Note: Perl's
sortis a merge sort and, in practice, stable: elements that compare as equal keep their original order. Adduse sort 'stable';if your code depends on it.
Sorting by several keys
Chain comparisons with or (or ||): if the first comparison says "equal" (0), the next one decides:
use strict;
use warnings;
my @players = (
{ name => "Kai", team => "red", score => 30 },
{ name => "Ana", team => "blue", score => 45 },
{ name => "Bo", team => "red", score => 45 },
{ name => "Cy", team => "blue", score => 30 },
);
for my $p (sort { $b->{score} <=> $a->{score} or $a->{name} cmp $b->{name} } @players) {
printf "%-4s %-5s %d\n", $p->{name}, $p->{team}, $p->{score};
}Ana blue 45
Bo red 45
Cy blue 30
Kai red 30
Highest score first, and alphabetical by name among equal scores.
Sorting hash keys by value
use strict;
use warnings;
my %visits = (home => 1520, about => 230, blog => 980, contact => 230);
my @by_traffic = sort { $visits{$b} <=> $visits{$a} || $a cmp $b } keys %visits;
printf "%-8s %5d\n", $_, $visits{$_} for @by_traffic;home 1520
blog 980
about 230
contact 230
Named comparison subs
A comparator can be a named sub, which is useful for reuse:
use strict;
use warnings;
sub by_version {
my @x = split /\./, $a;
my @y = split /\./, $b;
return $x[0] <=> $y[0] || $x[1] <=> $y[1] || $x[2] <=> $y[2];
}
my @releases = qw(1.10.0 1.2.3 1.2.10 0.9.9 1.2.9);
print join(" ", sort by_version @releases), "\n";0.9.9 1.2.3 1.2.9 1.2.10 1.10.0
A plain string sort would put 1.10.0 before 1.2.3.
The Schwartzian transform
When computing the sort key is expensive, a comparator recomputes it on every comparison, roughly n log n times. The Schwartzian transform (named after Randal Schwartz) computes each key once using a map-sort-map pipeline. Read it from the bottom up:
use strict;
use warnings;
my @files = ("report-2024-03.txt", "notes-2023-11.txt", "summary-2024-01.txt", "draft-2023-02.txt");
my @sorted =
map { $_->[1] } # 3. keep only the original value
sort { $a->[0] cmp $b->[0] } # 2. sort by the precomputed key
map { [ (/(\d{4}-\d\d)/)[0], $_ ] } # 1. pair each value with its key
@files;
print "$_\n" for @sorted;draft-2023-02.txt
notes-2023-11.txt
summary-2024-01.txt
report-2024-03.txt
- The first
mapturns each file name into a pair[key, original], where the key is the date extracted by a regex. sortcompares only the cheap, precomputed keys.- The last
mapthrows the keys away.
Other sorting helpers
use strict;
use warnings;
use List::Util qw(uniq);
my @tags = qw(perl Code perl regex code Perl);
my @unique_sorted = uniq sort { lc($a) cmp lc($b) or $a cmp $b } @tags;
print "@unique_sorted\n";
my @nums = (5, 3, 9);
@nums = sort { $a <=> $b } @nums; # sort "in place" by assigning back
print "@nums\n";
print "Reversed: @{[ reverse sort { $a <=> $b } @nums ]}\n";Code code Perl perl regex
3 5 9
Reversed: 9 5 3
Test yourself
Which call sorts numbers from largest to smallest?
sort @nsort { $a <=> $b } @nsort { $b <=> $a } @nsort { $a cmp $b } @n
What does sort (3, 20, 100) return?
(3, 20, 100)(100, 20, 3)(20, 3, 100)(3, 100, 20)
What is the purpose of the Schwartzian transform?
- To sort hashes
- To compute each expensive sort key only once
- To make sort stable
- To sort in reverse