PBP: 100 Reversing Lists

Mr. Conway suggets using the reverse builtin when appropriate.  This includes with sort, and for counting backwards.

I did not know this, but ‘reverse sort’ is recognized by the interpreter, and optimzed for, and it can be faster than sort { $b cmp $a }.  Neat!  It’s also a little more verbose, and states clearly what’s being done.

Reverse in for loops is also optimized, and means you can use the perl-style for and not the three-parameter C style one.  It may be clearer to write “for(reverse 10..20)” than “for($_ = 10; $_ > 20; $_–)”.  I don’t mind the C style, but it drives a lot of people crazy.

Reverse is a good choice.

 

2 Responses to “PBP: 100 Reversing Lists”

  1. Salva says:

    ‘sort { $b cmp $a } @data’ is also recognized by the interpreter.

    Also, ‘reverse sort { CMP($a, $b) } @data’ and ‘sort { CMP($b, $a) } @data’ are not completely equivalent operations. In the second case the sort is stable.

  2. MidLifeXis says:

    I think you have the endpoints in your last for loop reversed. If not, EMORECOFFEE.

Leave a Reply to MidLifeXis