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

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;

Spread the Word:
  • Digg
  • del.icio.us
  • StumbleUpon
  • Slashdot
  • Netvouz
  • description
  • blogmarks
  • Furl
  • IndiaGram
  • IndianPad
  • Reddit
  • Simpy
  • e-mail
  • Facebook
  • Google
  • Live
  • Technorati
  • YahooMyWeb
  • TwitThis

RSS feed | Trackback URI

Comments »

No comments yet.

Name (required)
E-mail (required - never shown publicly)
URI
Subscribe to comments via email
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post

139897 pages viewed, 70 today
59394 visits, 34 today
FireStats icon Powered by FireStats