Your code only returns the oldest file if ls sorts by time. Maybe your ls is an alias. Anyway:
my %stats; for (<*>) { my $mtime = (stat)[9]; ## for atime, use (stat)[8] push @{$stats{$mtime}}, $_; } my $oldest = (sort { $a <=> $b } keys %stats)[0]; print "oldest: ", (join ',', @{$stats{$oldest}}), "\n";
Here's another version that doesn't eat so much memory:
my ($timestamp, $files) = ~0; for (<*>) { my $mtime = (stat)[9]; ## for atime, use (stat)[8] if ($mtime < $timestamp) { $timestamp = $mtime; $files = [ $_ ]; } elsif ($mtime == $timestamp) { push @{$files}, $_; } } print "oldest: ", (join ',', @{$files}), "\n";
I'm thinking of some way of doing it with map. This somewhat golfed version uses GRT for sorting and returns only one file:
Update: Fixed sort numerically vs ASCIIbetically. Added two more versions.
--
David Serrano
In reply to Re: grab oldest file
by Hue-Bond
in thread grab newest file
by hasimir44
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |