O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required