As others pointed out, it's good form to use YYYYMMDD. But in case you can't:
#!/usr/bin/perl -w use strict; my $DIR = '.'; use File::Find qw( find ); use File::Spec::Functions qw( catfile ); use Time::Local qw( timelocal ); my $todaysfile = catfile($DIR, time_to_filename(time)); if (! -e $todaysfile) { if (my $oldfile = find_latest_file($DIR)) { email_to_a_specific_person($oldfile); } } open FILE, ">>$todaysfile" or die qq{Can't open "$todaysfile": $!}; print FILE "Hello, World!\n"; close FILE; exit 0; sub find_latest_file { my ($dir) = @_; my ($bestfile, $latest) = (undef, 0); find sub { my $time = filename_to_time($_) or return; if ($time > $latest) { ($bestfile, $latest) = ($File::Find::name, $time); } }, $dir; return $bestfile; } sub filename_to_time { my ($filename) = @_; # Adjust if necessary my ($m, $d, $y) = $filename =~ /(\d\d)(\d\d)(\d\d)/ or return; return timelocal(0, 0, 0, $d, $m - 1, $y); } sub time_to_filename { my ($time) = @_; # Adjust if necessary my @localtime = localtime $time; my ($d, $m, $y) = @localtime[3, 4, 5]; my $filename = sprintf("%02d%02d%02d.txt", $m+1, $d, $y%100); return $filename; } sub email_to_a_specific_person { my ($file) = @_; print "Sending $file . . .\n"; }
If you are planning on running more than one copy of the program at once, then this code will sometimes fail, and you will need to investigate file locking.
I should've used strftime() from POSIX and could've used reduce() from Scalar::Util. Note that find_latest_file() runs in O(n), which might make a difference (versus an n log n sort) after a few years.
In reply to Re: Find a file
by TilRMan
in thread Find a file
by Midnite
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |