Perl-chick has asked for the wisdom of the Perl Monks concerning the following question:

Below is a code that extracts dates from files in a given directory. What i need help with is now getting these dates to print out in a dd-mmm-yyyy format?? I think the answer lies with putting the date, month and year values found into variables (backreferencing in pattern matching), then manipulating the contents of those variables as strings in order to get the required results.
$month = '(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)? |Apr(?:il)?|May|Jun(?:e)? |Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)? |Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+'; $day = '[0-3]?[0-9](?:th|st|nd|rd)?,?\s+'; $year = '[0-9]{2,4}'; $dir= "c:/texts/"; $out="c:/scripts/out.txt"; open OUT, ">$out" or die "Cannot open $out for write :$!"; opendir(DIRECTORY, $dir) or die "Can't open $dir: $!\n"; while($file = readdir DIRECTORY){ next if $file=~/^\./; $rfname=$dir . $file; open (CONT, $rfname); while (<CONT>){ if(/( (?:${day}${month}${year}) | (?:${month}${day}${year}) ) /ixo) { print OUT "$file\t $1\n"; } } }
thanks in advance...

Replies are listed 'Best First'.
Re: Data normalisation
by splinky (Hermit) on Jul 06, 2000 at 17:28 UTC
    First off, kudos on that regex. Very spiffy. Are you aware of qr/REGEX/ in newer Perls?

    As to the problem at hand, yes, you're going to have to use capturing parens and manipulate the results. Something like the following in your if condition:

    if ((($month, $day, $year) = /($month)($day)($year)/io) || (($day, $month, $year) = /($day)($month)($year)/io)) { .... }

    Then, the question becomes, what goes in the "...."? I'll assume you have a plan in mind for $year, and $day doesn't require anything unless you want to do verification. My suggestion for $month is a hash that looks something like this:

    JANUARY => 'Jan', FEB => 'Feb', FEBRUARY => 'Feb', .... DEC => 'Dec', DECEMBER => 'Dec');

    Then you can so something like:

    printf('%02d-%s-%04d', $day, $mhash{uc $month}, $my_year);

    where $my_year is something you calculated from $year.

    Of course, if you want to validate the day first, you could augment %mhash something like this:

    my %mhash = (JAN => {Name => 'Jan', Days => 31}, ....

    And print like so:

    printf('%02d-%s-%04d', $day, $mhash{uc $month}{Name}, $my_year);

    That was probably more answer than you needed, but there ya go.

    *Woof*

      Actually, I need to amend the above a bit. Looking at your regexes again, I just realized that you'll have to put some capturing parens in them to keep everything happy, and stick undefs in the "if" clause accordingly.

      E.g.,

      $day = '([0-3]?[0-9])(?:th|st|nd|rd)'

      And in the if, something like:

      if ((($month, undef, $day, $year) = /($month)($day)($year)/io) ||

      I didn't go through your regexes and if clauses and give you the exact solution, but I think you get the idea.

      *Woof*

Re: Data normalisation
by Ovid (Cardinal) on Jul 06, 2000 at 20:39 UTC
    I just wanted to respectfully disagree with ZZamboni's putting the capturing parentheses in the variable assignments as opposed to the regex. Generally, when you have a complicated code that is well-developed but has a general use, don't throw anything in there which is irrelevant to the purpose of that code.

    In this particular case, you are simply defining $month, $day, and $year, as was done in the original regex. This is good. However, the actual capturing of the values is not done until the regex and the capturing parens should be listed in the regex, not in the variable assignment. Imagine what would happen the first time another programmer (or yourself, several years later) comes along and tries to reuse that code.

    print $1 if /(${month}${day}${year})/io;
    The above code would work, but what if someone just wants the year?
    print $1 if /${month}${day}(${year})/io;
    Oops! Now our code is broken because the capturing parentheses were put into the variable assignment rather than placed directly in the regex. This could be very confusing to debug.

    The moral of this tale? Make each little snippet of code as generic as possible and when something needs to be done (such as capturing a value to $1), do it where it's being done. Don't hide it somewhere else.

    As a side note, I noticed that everyone has dropped the curly braces {} from around the variables. While I will admit that the curly braces are not strictly necessary in the example, I like them for two reasons:

    1. If you are used to them, they make the variables stand out (IMHO)
    2. In complicated regexes using variable interpolation, they can help to guarantee that the regex compiler is examining the variable you are expecting, rather than pulling in extra characters into your variable name.
    The last point may seem strange, but I've been bitten by this more than once. The compiler has given me warnings about using variables in the regex that haven't been declared. By putting them in the curly braces, all warnings went away. It's a habit for me now.

    Incidentally: Perl-chick's code is from a response to this node.

      This is a very good point, Ovid. Sometimes the easiest solution may not be the most maintenable one. In fact, putting the grouping parenthesis in the regex instead of in the variable assignments only adds a little bit of postprocessing. You only need to remove the possible suffixes from $day. So something like this would work:
      if (( ($m, $d, $y) = (/($month)($day)($year)/io) ) || ( ($d, $m, $y) = (/($day)($month)($year)/io) ) ) { $y += 1900 if $y < 100; $m = substr($m, 1, 3); $d =~ s/^(\d+).*$/$1/; print "$d-$m-$y\n"; }
      Another thing I noticed is that we had been happily assigning the matching strings to the same variables used to hold the regular expressions. Not good. So I renamed the variables in this new code segment.

      --ZZamboni

        We had been happily assigning the matching strings to the same variables used to hold the regular expressions.

        ROTFL!!! I can't stop laughing over this one. Whups!! :)

Re: Data normalisation
by ZZamboni (Curate) on Jul 06, 2000 at 18:23 UTC
    Like splinky mentioned, you will have to add some backreferencing parenthesis to your regexes, like this:
    $month = '(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)? |Apr(?:il)?|May|Jun(?:e)? |Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)? |Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+'; $day = '([0-3]?[0-9])(?:th|st|nd|rd)?,?\s+'; $year = '([0-9]{2,4})';
    Note that I removed the ?: from the outermost parenthesis in $month, and added them to $day and $year. Then you could do something like this:
    if (( ($month, $day, $year) = (/$month$day$year/io) ) || ( ($day, $month, $year) = (/$day$month$year/io) ) ) { $year += 1900 if $year < 100; $month = substr($month, 1, 3); print "$day-$month-$year\n"; }
    The if statement was copied from splinky's response, but I removed the parenthesis from the regex because they are already in the variables. You may want to fix the $year adjustment to properly handle things.

    --ZZamboni