I am trying to code a Perl Script which will take the date in Pattern, October 24, 2011 and convert this to 10,24,2011.
In order to do this I have prepared a Hash which will have the Month Name as a Key and a Numerical value representing Month’s position as a Value.
I will read the input string, use a regular expression to extract the month name from above format.
Replace this month name with a value which corresponds to the month as a key.
Here’s the script I have coded so far, but it’s not working for me.
@dates array will have every element in this format -> October 24, 2011.
%days=("January",01,"February",02,"March",03,"April",04,"May",05,"June",06,"July",07,"August",08,"September",09,"October",10,"November",11,"December",12);
@output = map{
$pattern=$_;
$pattern =~ s/(.*)\s/$days{$1};
} @dates;
foreach $output (@output)
{
print $output."\n";
}
Here’s a little explanation of what I am trying to do with this code.
@output will have the new formatted array with the Month Name replaced by the corresponding Numerical representing it as defined in the Hash.
map function is used to transform the elements of the array on the fly.
a sequence of characters followed by space is the regular expression used to extract the Month Name from pattern, October 24, 2011.
This will be referenced by $1.
I look up the corresponding value for $1 in the hash using, $days{$1}
I see a few problems here. The first is that there is no
use strict;.A number with a leading zero is assumed to be in octal format (i.e. base 8) so
08is invalid. You want one of these:You should also be declaring your variables with
my:You’re missing the final slash on your substitution, you probably want a comma in there to match your desired output format, and
.*will eat up more than you want:The block for your
mapneeds to return the value you want in@outputbut it currently returns 1 (seeperldoc perlopto learn why); something like this will serve you better:If you really want the spaces removed from the output, then this should do the trick:
There are more compact ways to do this
mapbut I don’t want to change too much and confuse you.And, as mentioned in the comments, you might want to save yourself some trouble and have a look at
DateTimeand related packages.