Tips Tricks Tutorials

WEB-NES-BAY

Learn Tips and tricks on Linux, Hacking, linux, PHP, Perl, Web, Hardware

bookmark bookmark
WEBNESBAY On October - 31 - 2009

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.

Source

Related posts:

  1. How to sort IP Addresses in python
  2. Assigning lists and arrays in PERL
  3. List Extract and Compact simple but very useful functions in php
  4. Special shortcuts in Perl
  5. Perl Server Side CGI Scripting
  6. How to run another program from perl
  7. Create PDF using perl
  8. Run IMAP with PERL
  9. Perl script for search & replace in several files
  10. search & replace in several files in perl script
Categories: Perl

Leave a Reply