O'Reilly logo

Perl for Web Site Management by John Callender

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

Fancier Sorting

As you learned back in Chapter 6, we can customize how the sort function sorts things by giving it an explicit sort block, which is a curly-brace-delimited block containing instructions on how to sort two special variables, $a and $b.

Let’s look at some examples, working from simple sorts to more complex ones:

@ary    = ('b', 'c', 'a');

@sorted = sort @ary;                # @sorted gets: a, b, c
@sorted = sort { $a cmp $b } @ary;  # same thing
@sorted = sort { $b cmp $a } @ary;  # reversed: c, b, a

This first example demonstrates something you already learned back in Chapter 6. Namely, that the cmp string-comparison operator, used in the sort block { $a cmp $b }, gives the same result as sort’s default behavior, which is to sort a list into ascending ASCII order. It also demonstrates something you haven’t seen before: how to sort in descending order. You do that simply by switching the places of the $a and $b variables in the sort block.

Since ASCII order gives case-sensitive sorting, with all the uppercase letters sorting first, here’s a technique (also demonstrated back in Chapter 6) to overcome that behavior in situations where you actually want case-insensitive sorting:

@ary    = ('b', 'c', 'a', 'Y', 'X', 'Z');

@sorted = sort { $a cmp $b } @ary; # case-sensitive ASCII-order sort.
                                   # @sorted gets: X, Y, Z, a, b, c
                                         
@sorted = sort { lc $a cmp lc $b } @ary; # case-insensitive sort, now.
                                         # gives: a, b, c, X, Y, Z

All this is fine when you want to sort strings, but what about sorting numbers? ...

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