Advanced Sorting

Earlier, in Chapter 3, we showed that you could sort a list in ascending ASCIIbetical order by using the built-in sort operator. What if you want a numeric sort? Or a case-insensitive sort? Or maybe you want to sort items according to information stored in a hash. Well, Perl lets you sort a list in whatever order you’d need; you’ll see all of those examples by the end of the chapter.

You’ll tell Perl what order you want by making a sort-definition subroutine, or sort subroutine for short. Now, when you first hear the term “sort subroutine,” if you’ve been through any computer science courses, visions of bubble sort and shell sort and quick sort race through your head, and you say, “No, never again!” Don’t worry; it’s not that bad. In fact, it’s pretty simple. Perl already knows how to sort a list of items; it merely doesn’t know which order you want. So, the sort-definition subroutine simply tells it the order.

Why is this necessary? Well, if you think about it, sorting is putting a bunch of things in order by comparing them all. Since 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 and caboodle in line. Perl already understands all of those steps except for the part about how you’d like to compare the items, so that’s all you have to write.

This means that the sort subroutine doesn’t need to sort many items after all. It merely has to be able to compare two items. ...

Get Learning Perl, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.