typestar

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

  1. { $a <=> $b } compares numerically; swapping $b and $a reverses the order.
  2. The default sort is ASCII-betical, so lc on both sides of cmp makes it case-insensitive.
  3. Any expression works as a key: comparing length($a) to length($b) sorts shortest first.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Lists & context, step 12 of 27 in Language basics.

← Previous Next →