Hi Monks

Sorry if my question is a little basic. I know some basic pattern matching, and have tried the tutorials section, but I'm still having a little trouble with the following task.

I have a load of date/time strings that have the following format:
mmm d{d} yyyy hh:mm:ss:sss{AM/PM}

eg. Oct 16 2004 11:09:19:943AM (example 1)
or Mar 3 2007 10:30:31:170PM (example 2)

What I want to do is to extract the day, month and year, and stick them together in the format yyyymmdd so I can sort by date easily. So for the above examples you'd get:
20041016 and
20070303

I've tried the following bit of code:

if ($data=~/(\D{3}) *?(\d{1,2}) *?(\d{4})/) # i.e. look fo +r 3 non-digits, then any number of spaces, then either 1 or two digit +s, then any number of spaces, then 4 digits. (I wasn't sure how many +spaces separated each part.) { $month= $datehash{$1},br; # datehash is a lookup for th +e month $day=$2; if ($day=~/\d{1}/) { $day='0'.$day; # i.e. add a '0' in front of days consistin +g of 1 digit, so 16 stays as 16, but 1 turns into 01 } $year=$3; $sortingdate=join '', $year, $month, $day; }
Now this works for example 2 (I do get 20070303), but not for example 1: for some reason I get 1016 instead of 20041016. Why?

In reply to 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.