Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I am looking to parse the year out of several lines, I have a loop created but I am not sure how to use regular expressions to parse it. Any help would be greatly appreciated.
1/26/2005 9:58:31 AM 2/2/2005 12:54:16 PM 2/4/1997 3:58:31 PM 2/4/2005 3:58:54 PM 2/4/2001 4:36:59 PM 2/4/2005 4:37:15 PM 2/4/2005 7:57:51 PM 2/4/2002 7:58:05 PM 2/7/2003 11:35:10 AM 2/10/2005 11:41:56 AM
Thanks,
Michael

Replies are listed 'Best First'.
Re: Parsing the year out of date
by Limbic~Region (Chancellor) on Oct 20, 2005 at 16:55 UTC
    Michael,
    You will inevitably be pointed to one of a myriad of modules on CPAN to do this. The reason being is that, generally speaking, using regexes to parse dates has the same problems as IP addresses, email addresses, HTML, XML, etc. These modules may still use regexes but they are more robust and have considered far more edge cases then the casual user trying to solve the problem for the first time.

    On the other hand - if you are absolutely sure of your data then using a regex may be a fine way to go.

    my $year = (split m|[/ ]|, $date)[2];

    Cheers - L~R

Re: Parsing the year out of date
by borisz (Canon) on Oct 20, 2005 at 18:56 UTC
    Or just grab the first four digits.
    my ( $y ) = /(\d{4})/;
    Boris

      borisz meant the first group of four digits, which is perfect if you can count on the data format.

      Why not do your loop all in one line?

      my @years = map /(\d{4})/, @dates;

      Of course, you could use any regex that satisfies in the code above. Note that the parenthesis are critical, without them you'll wind up with a list full of '1'.

      Update Thanks to Roy Johnson I fixed my regex. Left out the \ for the \d.


      TGI says moo

Re: Parsing the year out of date
by ambrus (Abbot) on Oct 21, 2005 at 15:27 UTC

    You install the Date::Manip module, and then

    use Date::Manip; $datestr = "1/26/2005 9:58:31 AM"; $year = UnixDate($datestr, "%Y");
    gives the year.