Perl Printing a matching substring

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


18 points

Hi all,

I need a perl script that can open files (given in command line arguments) and extract/print out any dates or times found in it. The format of the dates and times can be any reasonable format.

The problem I have is I don't know how to print out the matching part of the file once i find it. Any ideas?



-1 points

Using regular expressions as follows on the command line:

 perl findtime.pl date_file.txt 

The code for findtime.pl is as follows:

#!/usr/bin/perl
#findtime.pl
use strict;
use warnings;
 
my $d1 = qr{(?:0[1-9]|1[012])[- /.](?:0[1-9]|[12][0-9]|3[01])[- /.](?:19|20)\d\d}; #Matches mm/dd/yyyy
my $d2 = qr{(?:0[1-9]|[12][0-9]|3[01])[- /.](?:0[1-9]|1[012])[- /.](?:19|20)\d\d}; #Matches dd/mm/yyyy
my @dates;
 
while (<>){
	my @d = m/$d1 | $d2/gx;
	push @dates, @d if scalar(@d);
}
 
print "$_ \n" foreach @dates;

The file 'date_file.txt' contains the data.

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.