This program is going to print files that have an
mtime during the previous Monday (a 24 hour period).
On line 11, $start is intialized to midnight of the
current day. $start is expressed as a number of seconds
from what is called the "epoch".
Now we have to "back up" from the current day's midnight to the previous Monday.
If today was say Tuesday, then dow would be 2.
while ($dow != $target_dow) would be while (2 != 1){}. A day's worth of seconds
are subtracted from $start, $dow is decremented,
loop stops.
if (--$dow < 0) { $dow += 7;} What happens if we were
starting on Sunday, $dow of 0?. We have problems because current dow (0) is less than the Monday (1). We are one week off. We want to count: 6,5,4,3,2,1,
winding up subtracting 6 full days of seconds, hence the reason to add 7.
There is more than one way to do this, but we are essentially "counting" in a circle, imagine a roulette wheel where the numbers around the circle are 0,1,2,3,4,5,6,7. Wheel in the case only goes anti-clockwise. Hope that analogy works for you.
Once the proper Monday "start date" is figured out, then my $stop = $start + $seconds_per_day; adds one day of seconds to it.
Here is full code without line numbers (one subroutine was left out):
#!perl
use strict;
use warnings;
use utf8;
use File::Find;
use Time::Local;
my $target_dow = 1; # Sunday is 0, Monday is 1, ...
my @starting_directories = (".");
my $seconds_per_day = 24 * 60 * 60;
my($sec, $min, $hour, $day, $mon, $yr, $dow) = localtime;
my $start = timelocal(0, 0, 0, $day, $mon, $yr); # midnight tod
+ay
while ($dow != $target_dow) {
# Back up one day
$start -= $seconds_per_day; # hope no DST! :-)
if (--$dow < 0) {
$dow += 7;
}
}
my $stop = $start + $seconds_per_day;
my($gather, $yield) = gather_mtime_between($start, $stop);
find($gather, @starting_directories);
my @files = $yield->( );
for my $file (@files) {
my $mtime = (stat $file)[9]; # mtime via slice
my $when = localtime $mtime;
print "$when: $file\n";
}
sub gather_mtime_between{
my ($begin, $end) = @_;
my @files;
my $gatherer = sub {
my $timestamp = (stat $_)[9];
unless (defined $timestamp){
warn "Can't stat $File::Find::name $!, skipping\n";
return;
}
push @files, $File::Find::name
if $timestamp >= $begin and $timestamp <= $end;
};
my $fetcher = sub {@files };
($gatherer, $fetcher);
}
|