I have a certain directory, and I want to find the most recently modified file in that directory and extract the time that it was last modified in Perl.
Can you suggest how I can go about doing this ?
Printable View
I have a certain directory, and I want to find the most recently modified file in that directory and extract the time that it was last modified in Perl.
Can you suggest how I can go about doing this ?
Well, you will have to loop through all of them and compare them. The following code will get you the last modified date.
Code:open(HANDLE, $filename);
localtime((stat HANDLE)[9]);
...
Or including the loop (I was writing the full version as PeejAvery responded...)
This won't work in all cases, but should get you started... This is also designed to handle multiple files with the same modified time.
Code:use strict;
my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my $directory = $ARGV[0] || "./"; #Get the directory from the argument line or use the local directory
opendir(DIR, $directory) || die "Can't open directory $directory: $!\n";
my %latestmodifiedfiles = undef;
my $latestfiletime = 0;
while (defined(my $file = readdir(DIR)))
{
# Get file stats
my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($file);
# Check if the modified time is null, if so skip...
if ($mtime ne "")
{
# Check if the modified time is greater than the last modified time
if ($mtime > $latestfiletime)
{
# if so, clear the hash and add the new filename to it - set the latest file time equal to said value.
%latestmodifiedfiles = undef;
$latestmodifiedfiles{$file} = "1";
$latestfiletime = $mtime;
}
# Check if the times are equal - if so, add filename to the hash
elsif ($mtime == $latestfiletime)
{
$latestmodifiedfiles{$file} = "1";
}
}
# Otherwise, skip...
}
closedir(DIR);
# Now iterate through the files in the hash and display the file time
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime($latestfiletime);
foreach my $file (keys %latestmodifiedfiles)
{
if ($file ne "." && $file ne "")
{
print "$file: " . sprintf("%02d:%02d:%02d", $hour,$min,$sec) . " $abbr[$mon] $mday " . sprintf("20%02d", $year % 100) . "\n";
}
}
thanks guys thats very helpful
do you know if the file modified time on the containing directory will also be the same as the most recently modified file's modified time ?
Just wondering if it would be simpiler to get the modified time from the directory instead ?
so in other words would something like this work ?
just guessing from looking at your codeCode:
open(DIR, $directory);
$modified = localtime((stat DIR)[9]);
That may work, I'm not really sure...