Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2009

    Unanswered: Finding the latest modified file in a directory


    I am trying to find the latest modified file in a directory and do something with it like move or copy.

    I am trying to read the directory and get the latest modified file in a windows folder using the below code but it is not giving me the latest modified file.

    #!/usr/local/bin/perl -w
    use warnings;

    my $directory = 'C:\\Perl\\site\\lib\\new';
    opendir(DIR2, $directory) or die "Can't open $directory: $!";
    @files = readdir(DIR2);

    @sorted = sort {-M "$directory$a" <=> -M "$directory$b"} @files; #sort them by modification date most recent to least recent
    print "The most recent modified file is: $sorted[0]";

    Any help would be appreciated.

    Last edited by pradee; 09-01-09 at 03:54.

  2. #2
    Join Date
    Oct 2002
    Baghdad, Iraq
    Should be $directory\\$file.

    Incidentally, you might try doing this if you have a huge number of files:

    %h = map(($_, -M "$directory\\$_"), @files);
    @files = sort { $h{$a} <=> $h{$b} } @files;
    Hitting stat (or the Win32 equivalent) is fairly expensive. You could make it even faster by rolling the -M values into the keys and using straight sort(@files), but that's often overkill.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts