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
dan September 9th 2008

me too! thanks.

RD October 23rd 2008

Dude... sweet !

sakthi July 16th 2009

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

Devin November 27th 2009

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

Hazhir March 9th 2010

thank you...

chris September 3rd 2010

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

thank you.

DUDE February 24th 2011

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.

Jeff January 14th 2012

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'};

THIS IS WRONG July 15th 2016

Loser.

Matt December 20th 2017

A decade later, search, cut and paste!

All content licensed under the Creative Commons License