I have reformatted your code to make it more readable:
if ($data=~/(\D{3}) *?(\d{1,2}) *?(\d{4})/) { $month = $datehash{$1}; $day=$2; if ($day=~/\d{1}/) { $day='0'.$day; } $year=$3; $sortingdate=join '', $year, $month, $day; }
Your regular expression is okay, as far as it goes. The error is in the formatting. The test $day=~/\d{1}/ will match every one- or two-digit day specification, so you will always add a zero. Also, do the values of %datehash have leading zeroes where required? Here is how I would re-write your code:
my %datehash; @datehash{ qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) } = map sprintf( '%02d', $_), 1 .. 12; my $mon_re = join '|', keys %datehash; while ( <DATA> ) { my ( $mon, $day, $year) = /($mon_re)\s+(\d\d?)\s+(\d{4})/; $day = sprintf '%02d', $day; print "$year$datehash{ $mon}$day\n"; } __DATA__ Oct 16 2004 11:09:19:943AM Mar 3 2007 10:30:31:170PM
I have made the regular expression more specific for the month names (since %datehash is already there) and less specific for white space (allowing any, not only blanks).

Anno


In reply to Re: Pattern matching for extracting dates by Anno
in thread Pattern matching for extracting dates by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.