aatlamaz has asked for the wisdom of the Perl Monks concerning the following question:

I am able to find the latest file in my directory by using following code, but I need to find the newest file as well. Any idea how to do that? Is there any PM for that? Thanks
my $dir = "C:\\Perl"; opendir DH, $dir or die "Cant open $dir: $!"; foreach $file (readdir DH) { print "files in $dir id $file\n"; } closedir DH; my $oldest; my $oldtime = 0; for (glob "$dir/*") { my $thistime = -C; if ($thistime > $oldtime) { ($oldest, $oldtime) = ($_, $thistime); } } printf "The oldest file was %s, and it was %.1f days old.\n", $oldest, + $oldtime;

Replies are listed 'Best First'.
Re: Finding Newest File in Perl
by zentara (Cardinal) on Dec 07, 2004 at 13:35 UTC
    Modify for either newest or latest:
    #!/usr/bin/perl $dir = shift || '.'; my $latest = (sort {$b->{mtime} <=> $a->{mtime}} map {{mtime => -M $_, file => $_}} <$dir/*>)[-1]; print $latest->{file}, "\n"; #Using map allows -M to be performed on each file only once #per sort iteration. #once will save a lot of CPU time.

    I'm not really a human, but I play one on earth. flash japh
      Thanks Guys, Thanks Zentara, it works great now!...
Re: Finding Newest File in Perl
by neniro (Priest) on Dec 07, 2004 at 10:53 UTC
    You can iterate over all those files. Test each file for it's timestamp. If it's bigger than the previous, store the file-name into a variable. That's it.