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”;

opendir DIR, “$dirname”;

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

5 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

  4. Hi blogger, do you monetize your website ? There is easy
    way to earn extra money every month, just search on youtube :
    How to earn $25/hour selling articles

  5. I still find it imperative that one meditates and creates just focusing the mind.

    Nevertheless, don’t go believing that motherhood defines a
    lady, it is simply a piece of her being. That way you remove each of the costs of making use of
    the trading platform offered to you and you also only pay a smaller brokerage fee that is shared amongst all the fund pool contributors as one entity handles the whole, larger pool.

Leave a Reply

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