Section 8.2. Reversing Lists


8.2. Reversing Lists

Use reverse to reverse a list.

By default, the sort builtin sorts strings by ascending ASCII sequence. To make it sort by descending sequence instead, you might write:

     @sorted_results = sort { $b cmp $a } @unsorted_results;

But the operation would be much more comprehensible if you wrote:

      @sorted_results = reverse sort @unsorted_results;

That is, if you sorted using the default ordering and then reversed the sorted results afterwards.

Interestingly, in many versions of Perl, it's just as fast (or occasionally even faster) to use an explicitly reversed sort. In recent releases, the reverse sort sequence is recognized and optimized. In older releases, sorting with any explicit block was not optimized, so calling sort without a block is significantly faster, even when the extra cost of the reverse is taken into account.

Another situation in which reversing a list can significantly improve maintainability, without seriously compromising performance, is when you need to iterate "downwards" in a for loop. Instead of writing:

     for (my $remaining=$MAX; $remaining>=$MIN; $remaining--) {         print "T minus $remaining, and counting...\n";         sleep $INTERVAL;     }

write:

      for my $remaining (reverse $MIN..$MAX) {         print "T minus $remaining, and counting...\n";         sleep $INTERVAL;     }

This approach makes it clear that you intended to count in reverse, as well as making the precise range of $remaining much easier to determine. And, once again, the difference in iteration speed is usually not even noticeable.

The loop itself is also more robust. In the first version, the C-like for relies on correct coordination among its three components to achieve the appropriate iteration behaviour. But in the second version, the Perl-like for is given an exact range to iterate, so it's less prone to incorrect choices of comparison operator, inappropriate updating of the iterator variable, or other bad interactions.



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net