Custom sort orders in Perl
sort takes a comparator block: <=> for numbers, cmp for strings, and anything you compute.
use strict;
use warnings;
my @nums = (10, 2, 33, 4);
my @words = ("pear", "Fig", "apple");
my @asc = sort { $a <=> $b } @nums;
my @desc = sort { $b <=> $a } @nums;
print "@asc\n";
print "@desc\n";
my @alpha = sort { lc($a) cmp lc($b) } @words;
print "@alpha\n";
my @by_len = sort { length($a) <=> length($b) } @words;
print "@by_len\n";
How it works
{ $a <=> $b }compares numerically; swapping$band$areverses the order.- The default sort is ASCII-betical, so
lcon both sides ofcmpmakes it case-insensitive. - Any expression works as a key: comparing
length($a)tolength($b)sorts shortest first.
Keywords and builtins used here
lclengthmyprintsortuse
The run, in numbers
- Lines
- 16
- Characters to type
- 340
- Tokens
- 116
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 99 seconds.
Step 3 of 3 in Lists & context, step 12 of 27 in Language basics.