Monday, December 19, 2016

Advanced sorting (multiple keys) in perl.

Sometimes you need to sort data like this:
1. Sort by numeric value first.
2. If numeric values are equal, sort by name.

Here's the code for doing this in perl :
Let's suppose I have a hash of hashrefs. (eg. $distance{$city}= $some_number).
This hash stores distances of citites (keys) from a particular city. Now we want to sort by distance first (ascending) and if two citites are at equal distance, we want to sort on the basis of names :

To sort on descending order, we just replace $a with $b and vice versa:

How does this work?

The <=> operator is equivalent to :

so if $a == $b we get to the second test for OR operator which compares the strings similarly. If even the names of strings are equal, we return 0 which tells the sort function that these two entries are equal and order for them doesn't matter to us.

No comments:

Post a Comment