Perl month hash

I'm really tired of retyping this:

my $mons = {
    'Jan' => 1,
    'Feb' => 2,
    'Mar' => 3,
    'Apr' => 4,
    'May' => 5,
    'Jun' => 6,
    'Jul' => 7,
    'Aug' => 8,
    'Sep' => 9,
    'Oct' => 10,
    'Nov' => 11,
    'Dec' => 12,
};

Then access it with $mons->{Jul} to get the number. Or you can flip it to get a mapping of numbers to months:

$rev = { reverse(%$mons) };
Leave A Reply - 10 Replies
Replies
September 9th 2008 - dan

me too! thanks.

October 23rd 2008 - RD

Dude... sweet !

July 16th 2009 - sakthi

my %months = { '1'=>'Jan','2'=>'Feb','3'=>'Mar','4'=>'Apr','5'=>'May','6'=>'Jun','7'=>'Jul','8'=>'Aug','9'=>'Sep','10'=>'Oct','11'=>'Nov','12'=>'Dec'};

Incase, you want the reverse one with strict

November 27th 2009 - Devin

Thanks, just what I needed and the #2 google result for "perl month"

March 9th 2010 - Hazhir

thank you...

September 3rd 2010 - chris

you, sir, just saved me 30 seconds, which i squandered thanking you.

thank you.

February 24th 2011 - DUDE

DUDE THE SYNTAX IS WRONG ITS () FOR HAS NOT {} ARRRGGGHHH YOU WASTED MY TIME DEBUGGING NOT helped.. BUT THANKS ANYWAY actually the months helped so i dont type tyhem in.

January 14th 2012 - Jeff

the code is right you just have to know how to get at the data

my %mons = ('Jan'=>1,'Feb'=>2,'Mar'=>3,'Apr'=>4,'May'=>5,'Jun'=>6, 'Jul'=>7,'Aug'=>8,'Sep'=>9,'Oct'=>10,'Nov'=>11,'Dec'=>12);

print $mons{'Jan'};

my $mon = {'Jan'=>1,'Feb'=>2,'Mar'=>3,'Apr'=>4,'May'=>5,'Jun'=>6, 'Jul'=>7,'Aug'=>8,'Sep'=>9,'Oct'=>10,'Nov'=>11,'Dec'=>12};

print $mon->{'Jan'};

July 15th 2016 - THIS IS WRONG

Loser.

December 20th 2017 - Matt

A decade later, search, cut and paste!

All content licensed under the Creative Commons License