Advanced Sorting
In Chapter 3, we showed 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? Maybe you want to sort items according to information stored in a hash. Well, Perl lets you sort a list in whatever order you need; you’ll see all of those examples by the end of the chapter.
You tell Perl what order you want by making a sort-definition subroutine, or sort subroutine for short. When you hear the term “sort subroutine,” if you’ve been through any computer science courses, visions of bubble sort, shell sort, and quick sort race through your head, and you say, “No, never again!” Don’t worry because it’s not that bad. In fact, it’s simple. Perl knows how to sort a list of items, but it doesn’t know which order you want. So the sort subroutine 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 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. If it can put two items in the proper order, Perl will be able to tell ...
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