Perl Tips Blog from Bay View Training

Bay View Training

Sorting in Reverse Order

in Data Structures, Perl Tips
by William Ward on August 8, 2008 12:16 pm

Say you have an array of names: @names=qw(Tom Dick Harry);

If you wanted to sort these, you could just use a simple sort() command: @sorted=sort(@names); That uses alphabetical order for sorting by default. The sort criteria is not given, but you could get the same results by giving a longer version of the sort function call, like so: @sorted=sort {$a cmp $b} @names;

Here, $a and $b are special variables which are used to compare two of the values in @names to see which should come first in the sort order. The cmp operator returns a positive value if $a > $b, a negative value if $a < $b, or zero if they are equal. By changing the formula that follows the sort keyword you can change the order of the sort function.

If you wanted to sort in reverse order, you could just use Perl’s reverse() function: @revsort=reverse(@sorted); or in one statement, @revsort=reverse sort @names;. This is inefficient however as it must make a temporary copy of the list of names, which could get expensive if the array is large. A more efficient way is to just change the sort criteria to produce the reverse result. @revsort=sort { $b cmp $a } @names;. Now, the values returned by cmp are the opposite of what they were above, and so the sort order is the opposite.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment