Advanced Sorting
Earlier,
you learned that you could take a list and sort it in ascending ASCII
order (as you do with strings) using the built-in
sort function. What if
you don’t want an ascending ASCII sort, but something else
instead, like a numeric sort? Well, Perl gives you the tools you need
to do the job. In fact, you’ll see that the Perl
sort is completely general and able to perform any
well-defined sort order.
To define a sort of a different color, you need to define a comparison routine that describes how two elements compare. Why is this necessary? Well, if you think about it, sorting is putting a bunch of things in order by comparing them all. Because you can’t compare them all at once, you need to compare two at a time, eventually using what you find out about each pair’s order to put the whole kit’n'caboodle in line.
The comparison routine is defined as an ordinary subroutine. This routine will be called repeatedly, each time passing two elements of the list to be sorted. The routine must determine whether the first value is less-than, equal-to, or greater-than the second value, and return a coded value (described in a moment). This process is repeated until the list is sorted.
To save a little execution speed, the two values are not passed in an
array, but rather are handed to the subroutine as the values of the
global variables
$a and
$b
. (Don’t worry: the original
values of $a and $b are safely
protected.) The routine should return any negative number if
$a is ...
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