Fancier Sorting
As you
learned back in Chapter 6, we can customize how the
sort function sorts things by giving it an
explicit sort block, which is a
curly-brace-delimited block containing instructions on how to sort
two special variables, $a and
$b.
Let’s look at some examples, working from simple sorts to more complex ones:
@ary = ('b', 'c', 'a');
@sorted = sort @ary; # @sorted gets: a, b, c
@sorted = sort { $a cmp $b } @ary; # same thing
@sorted = sort { $b cmp $a } @ary; # reversed: c, b, aThis first example demonstrates something you already learned back in
Chapter 6. Namely, that the
cmp
string-comparison operator, used in the
sort block {
$a
cmp
$b
}, gives the same result as
sort’s default behavior, which is to sort a
list into ascending ASCII order. It also demonstrates something you
haven’t seen before: how to sort in descending order. You do that
simply by switching the places of the $a and
$b variables in the sort block.
Since ASCII order gives case-sensitive sorting, with all the uppercase letters sorting first, here’s a technique (also demonstrated back in Chapter 6) to overcome that behavior in situations where you actually want case-insensitive sorting:
@ary = ('b', 'c', 'a', 'Y', 'X', 'Z');
@sorted = sort { $a cmp $b } @ary; # case-sensitive ASCII-order sort.
# @sorted gets: X, Y, Z, a, b, c
@sorted = sort { lc $a cmp lc $b } @ary; # case-insensitive sort, now.
# gives: a, b, c, X, Y, ZAll this is fine when you want to sort strings, but what about sorting numbers? ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access