Chapter 10. Practical Reference Tricks
This chapter looks at optimizing, sorting, and dealing with recursively defined data.
qw(Gilligan Skipper Professor Ginger Mary-Ann)
but gets pretty messy when we want to sort numbers:
The resulting list is
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
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
keyword and the list of things to sort. Within the sort block,
$b stand in for two of the items
will compare. If we’re sorting numbers, then
will be two numbers from our list.
The sort block must return a coded value to indicate the sort order.
$a comes before
$b in our desired sorting order, it should ...