Chapter 10. Practical Reference Tricks

This chapter looks at optimizing, sorting, and dealing with recursively defined data.

Fancier Sorting

Perl’s built-in sort operator sorts text strings in their code point text order[23] by default. This is fine if we want to sort text strings:

my @sorted = sort qw(Gilligan Skipper Professor Ginger Mary-Ann);

but gets pretty messy when we want to sort numbers:

my @wrongly_sorted = sort 1, 2, 4, 8, 16, 32;

The resulting list is 1, 16, 2, 32, 4, 8. Why didn’t sort order these properly? It treats each item as a string and sorts them in string order. Any string that begins with 3 sorts before any string that begins with 4.

If we don’t want the default sorting order, we don’t need to write an entire sorting algorithm, which is good news since Perl already has a good one of those. But no matter what sorting algorithm we use, at some point we have to look at item A and item B, and decide which one comes first. That’s the part we’ll write: code to handle two items. Perl will do the rest.

By default, as Perl orders the items, it uses a string comparison. We can specify a new comparison using a sort block that we place between the sort keyword and the list of things to sort.[24] Within the sort block, $a and $b stand in for two of the items sort will compare. If we’re sorting numbers, then $a and $b will be two numbers from our list.

The sort block must return a coded value to indicate the sort order. If $a comes before $b in our desired sorting order, it should ...

Get Intermediate Perl, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.