Skip to Content
Intermediate Perl, 2nd Edition
book

Intermediate Perl, 2nd Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
July 2012
Intermediate to advanced
396 pages
9h 16m
English
O'Reilly Media, Inc.
Content preview from Intermediate Perl, 2nd Edition

Chapter 10. Practical Reference Tricks

This chapter looks at optimizing, sorting, and dealing with recursively defined data.

Fancier Sorting

Perl’s built-in sort operator sorts text strings in their code point text order[23] by default. This is fine if we want to sort text strings:

my @sorted = sort qw(Gilligan Skipper Professor Ginger Mary-Ann);

but gets pretty messy when we want to sort numbers:

my @wrongly_sorted = sort 1, 2, 4, 8, 16, 32;

The resulting list is 1, 16, 2, 32, 4, 8. Why didn’t sort 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 4.

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 sort keyword and the list of things to sort.[24] Within the sort block, $a and $b stand in for two of the items sort will compare. If we’re sorting numbers, then $a and $b will be two numbers from our list.

The sort block must return a coded value to indicate the sort order. If $a comes before $b in our desired sorting order, it should ...

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.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Perl & LWP

Perl & LWP

Sean M. Burke
Advanced Perl Programming

Advanced Perl Programming

Sriram Srinivasan

Publisher Resources

ISBN: 9781449343781Errata Page