Tuesday, April 21, 2009

Perl power! Sorting dictionaries (or hashes in Perl lingo)

Theres a dictionary dict1 with keys key1, key2, etc such that $dict1{keyn} has a value which itself is a dictionary. Lets call this dictionary %subdict. Now subdict has different keys subkey1, subkey2 and so on such that $subdict{subkey5} = subvalue5.

Problem: How do I sort dict1 such that the keys are in the ascending order of subvalue5?

This would not be easy to do in a single line of code, unless of course the language is Perl! Ready? here it is:

dict1_keys_sorted = sort {$dict1{$a}{subkey5} cmp $dict1{$b}{subkey5}} keys %dict1

Lets take this apart. Going from the right side, you start of with dict1. Now, keys %dict1 returns a list of the keys. With the sort command being invoked, Perl feeds the first two values of the keys into $a and $b. So, $dict1{$a}{subkey5} gives the value of subvalue5 for that key value of dict1. The values are compared and depending on true or false value, it puts the value into the new list dict1_keys_sorted which is sorted.

Note: "cmp" is for sorting strings. To sort number use "<=>".

No comments: