I am working on some perl project. I have come across a situation where I need to sort the values in arrays in reverse order. I have done it very simply. I have an array of array: @array=qw(canada mexico usa);
Now I can use te sort() command to sort the above values in the array by giving the command: @sortthis=sort(@array); That uses alphabetical order for sorting by default. The sorting criteria is not given, but you can get same results by giving a longer version of the sort function call, like so: @sortthis=sort {$a cmp $b} @array;
Here, $a and $b are special variables which are used to compare two of the values in @array to see which should come first in the sort order. The cmp is a comparison 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: @reversesort=reverse(@sortthis); or in one statement, @reversesort=reverse sort @array;. 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. @reversesort=sort { $b cmp $a } @array;. Now, the values returned by cmp are the opposite of what they were above, and so the sort order is the opposite.
Tags: Alphabetical Order, Array Array, Arrays, Canada Mexico, Cmp, Comparison Operator, List Of Names, Mexico Usa, Perl Array, Perl Project, reverse sort, reverse(), Sort Command, Sort Criteria, Sort Function, Variables