Perl Anonymous Hashes as Lookup-tables

Today when munging some data in Perl I came up with a elegant way to use anonymous hashes as lookup tables.

In this case I wanted to translate month names to integers. Of course you could use a bunch of regular expressions to do so. But adhering to the Perl motto there is more than one way to do it I tried using an anonymous hash as a lookup table, like this:

1
2
3
4
5
$month = ${{
  'jan' =>  1, 'feb' =>  2, 'mar' =>  3,
  'apr' =>  4, 'may' =>  5, 'jun' =>  6,
  'jul' =>  7, 'aug' =>  8, 'sep' =>  9,
  'oct' => 10, 'nov' => 11, 'dec' => 12}}{$month};

I quite like this method as no extra variables are needed and you can use this to map many types of data to others.

Comments