Find the latest or newest modified file in a folder or directory with Perl


I’ve worked on and off with Perl, but really want to be more proficient with it. I will do more automation with Perl and will share it here for my reader and as a reference for myself. I just created a Perl tag on this blog.

Here is one script I cooked out today. It takes a directory / folder name as input, and return the latest or newest modified file. Suggestions welcome!
[sourcecode language=”perl”]
#use File::Copy;
use File::stat;

$dirname = shift or die “Please provide a directory to search for”;
$timediff=0;

opendir DIR, “$dirname”;

while (defined ($file = readdir(DIR)))
{
if($file ne “.” && $file ne “..”)
{
$diff = time()-stat(“$dirname/$file”)->mtime;
if($timediff == 0)
{
$timediff=$diff;
$newest=$file;
}
if($diff<$timediff) { $timediff=$diff; $newest=$file; } } } print $newest,"\n"; #copy("$dirname/$newest", "c:/work/$newest"); [/sourcecode]

,

4 responses to “Find the latest or newest modified file in a folder or directory with Perl”

  1. You can also use ls -t:


    0-13:19 djh@ratchet ~> ls -lt | grep ^- | head -1
    -rw-r--r-- 1 djh djh 7477585 Mar 30 14:38 djh_wordpress-2008-03-30.sql

  2. That’s really cool: grep for files, and then take the first line, I learned something already!

    Google is good, but sometimes a live and breathing expert can cut through the noise and point you to the right direction. Thanks!

    The script I wrote was intended primarily for work on Windows. I am digging the here document, along with variable interpolation to generate some cool sql script.

    Thanks for sharing!

  3. Thank you so much for your brief code and it helps me to understand a lot and easy my work

  4. how to give directory name Unrecognized character \xE2; marked by <– HERE after ft or die <– HERE near column 25 at five.perl line 4.i am getting this error

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.