Created
November 15, 2013 06:52
-
-
Save iandexter/7480229 to your computer and use it in GitHub Desktop.
Get newer or latest files in a directory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Time::Local; | |
use POSIX qw(strftime); | |
sub getlatest { | |
my $dir = shift; | |
my $pattern = shift; | |
my $dh; | |
$dir =~ s|/\z||; | |
my $today = timelocal(0, 0, 12, (localtime)[3..5]); | |
my $yesterday = $today - 24 * 60 * 60; | |
my $today_stamp = strftime("%d%m%Y", localtime($today)); | |
my $yesterday_stamp = strftime("%d%m%Y", localtime($yesterday)); | |
my $filename = $dir . "/" . $pattern . "_messages_" . $today_stamp . ".log"; | |
$filename = $dir . "/" . $pattern . "_messages_" . $yesterday_stamp . | |
".log" if (! -e $filename); | |
return $filename; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sub getnewer { | |
my $dir = shift; | |
my $pattern = shift; | |
my $dh; | |
$dir =~ s|/\z||; | |
opendir($dh, $dir) or die "Cannot open $dir: $!\n"; | |
my @files = map { [ stat "$dir/$_", $_ ] } grep(! /^\.\.?$/, readdir($dh)); | |
closedir($dh); | |
sub revbydate { $b->[9] <=> $a->[9] } | |
my @sorted = sort revbydate @files; | |
my @latest; | |
for (my $i=0;$i<4;$i++) { | |
my @newest = @{$sorted[$i]}; | |
my $name = pop(@newest); | |
push(@latest, $name); | |
} | |
my $filename = join ",", grep(/^$pattern/i, @latest); | |
return $dir . "/" . $filename; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment