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

Hello all,
I do have script that open files with filename matching this pattern: *Dec2003*.txt and processes them. Unfortunatelly, some of the files belongs to different month, (January) even though their name says *Dec2003*.txt. So for example this file:
-rw-r--r-- 1 user group 642 Dec 29 23:00 TA29Dec2003-0.zip.LOG.summary.txt
should be processed as December 2003, however, this file:
-rw-r--r-- 1 user group 628 Jan 1 01:14 TA31Dec2003-1.zip.LOG.summary.txt
should be processed as January 2004!
Here is the script:
#!usr/bin/perl -w use strict; use Fcntl qw[:flock]; my $impressions = 0; my$iofile = '/other/scripts/daniel/input/c07_impressions_io.info'; open (IO, $iofile) || die("Could not open file 1!"); while (<IO> ) { chop; (my$FH, my$output, my$file2check) = split (/\s+/, $_); open OUT, ">> $output"; chdir $FH or die "$!"; while (glob $file2check) { open FH, $_ or die $!; flock FH, LOCK_SH or die $!; while (<FH> ) { chomp; if ( /Impressions:/ ) { my($text, $value) = split(/:/, $_); $impressions += $value if ($value =~ /\d+/); } } close FH or die $!; } } print OUT 'Total impressions: ', $impressions or die $!;
the my$iofile contains: 1. where the files I am interested are, 2. where to write the total, 3. and then the pattern (*Dec2003*.txt)
Please advice.
Thank you for your time.

Replies are listed 'Best First'.
Re: How to process only files created on specific month?
by Zaxo (Archbishop) on Jan 23, 2004 at 20:49 UTC

    I assume that by "create" you mean the mtime shown in your ls output. You can use stat and localtime to get what you want.

    while (<*Dec2003*.txt>) { # this is a glob if ( (localtime( (stat)[9]))[4] == 11 ) { # open $_ and process it } }

    Update: Not_a_Number++ is correct. Repaired.

    After Compline,
    Zaxo

      if ( (localtime( (stat)[9]))[4] == 12 )...

      I think you mean:

      if ( (localtime( (stat)[9]))[4] == 11 )...

      ...since month numbering starts from zero (for January)

      :-)

      dave

      Hello Zaxo,
      how would you include the oposite situatuion? (File with name November, but with mtime shown sa December) In one script? Thank you.

        I'd quit messing with file names and just go by mtime. Here's a way to make an AoA of file names.

        my @files; while (<*.txt>) { push @{$files[ (localtime +(stat)[9])[4] ]}, $_; }
        That gives you the November files as @{$files[10]}. You may want to rewrite that to take account of years, too. A hash may be more convenient than an array.

        After Compline,
        Zaxo