use warnings;
use strict;
use DateTime;
use DateTime::Format::Strptime;
use Path::Class qw/dir/;
my $LOGPATH = '.';
my $STARTD = '2017-12-08';
my $NUMDAYS = 3;
my $PATTERN = '1.2.3.4';
my $strp = DateTime::Format::Strptime->new(on_error=>'croak',
pattern => '%Y-%m-%d', time_zone=>'local');
my $dt = $strp->parse_datetime($STARTD);
my @files;
for (1..$NUMDAYS) {
my $date = $dt->strftime('%Y-%m-%d');
push @files, sort grep { $_->basename=~/\.log\z/i }
dir($LOGPATH,$date)->children;
$dt->add(days=>1);
}
{ # in a new block for "local"
local *ARGV; @ARGV = @files;
while (<>) {
chomp;
if (/\Q$PATTERN\E/) {
print "$ARGV:$.: $_\n";
}
} continue { close ARGV if eof }
}
- It's very good you're using a module like Time::Piece for your date handling. Personally I like DateTime because it does a whole lot more, along with DateTime::Format::Strptime for parsing, which is why I used those above.
- I'm using Path::Class for getting filenames, where $_->basename=~/\.log\z/i matches those files whose names end in .log (case-insensitively).
- I used a trick and assigned the list of files to the special @ARGV variable, which normally holds the command line arguments, so that I can make use of Perl's special while (<>) loop, described in I/O Operators. Inside that loop, the current filename is stored in $ARGV, and the line number in $. - but see the documentation on eof as for why I need the snippet of code close ARGV if eof. (If all that is too much magic for now, you can also wrap the grepping code I showed at the top in a for my $filename (@files) { ... } loop.)
- As opposed to your description, I have taken the "number of days" to include the start day, since that makes more sense to me.
Update: Fixed this potential issue in the above example code.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.