Article written

  • on 17.10.2007
  • at 03:32 PM
  • by Naveen

Perl one-liner to sort a hash and return the top most key/value View Comments

Oct17

A while ago Deepz asked me whether we can sort a hash and print the top most key or value or both in a single line, in PERL. After a little permutation & combination, I wrote the following piece. I’m sure there must be a more elegant and efficient way of doing it, but this will also serve the purpose on most occasions and with a little tweaking can be applied to almost all hashes.

  • The code needs to be modified if the hash keys contain any digits
  • The sort algorithm can be changed as per the requirement, by default I’m sorting by hash values which are digits

print grep {s/\d//g} grep {/1/} map { $i+=1 , $_.=$i , “\n”} sort {$hash{$a} <=> $hash{$b}} keys %hash;

blog comments powered by Disqus

Naveen's Journal is powered by WordPress and FREEmium Theme.
developed by Dariusz Siedlecki and brought to you by FreebiesDock.com