This question appears a bit strange as normally one would know what the position the "month" is in the string. If that is the case, then no "foreach" would be required. But going with the problem statement...., I would add keys to the month hash with the full month rather than getting a substr of the first 3 letters. Also usually splitting on /\s+/ (the default split) will work out better than splitting on " " because there can be tabs or multiple spaces in the input that are hard to see. As another point, if this line comes directly from input, then splitting on /\s+/ eliminates the need for "chomp;" (\n is a space character).
sub num_month
{
my $date_line = shift; #like jan 12 2009 or january 12 2009
my %months = (JAN => '01', FEB => '02', MAR => '03',
APR => '04', MAY=> '05', JUN => '06',
JUL => '07', AUG => '08', SEP => '09',
OCT => '10', NOV => '11', DEC => '12',
JANUARY => '01, ....etc.....);
my (@tokens) = split (/\s+/, uc($date_line));
foreach my $token (@tokens)
{
return ($months{$token} if $months{$token});
}
die "no month in @tokens"; ## optional but you may want this
}
Note: if you omit the \n in the die "text", Perl will add the module and line number of the death to the output.
Update:
showing how slit on \s and , can be done and how to get say the 2nd thing in a split via a list slice without using foreach():
#!/usr/bin/perl -w
use strict;
my $date_line = "Jan 2 , 2009 \n";
my (@tokens) = split (/[\s,]+/, uc($date_line));
print "@tokens\n";
#prints JAN 2 2009
my $date_line2 = "2 jan , 2009 \n";
#to get 2nd thing in split, use a list slice...
my $month_text = (split (/[\s,]+/, uc($date_line2)))[1];
print "$month_text\n";
#prints JAN
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.