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!

#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");

3 thoughts on “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

Leave a Reply

Your email address will not be published. Required fields are marked *