If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Perl and the DBI > Finding the last modified file in a directory

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 08-28-09, 09:41
pradee pradee is offline
Registered User
 
Join Date: Aug 2009
Posts: 1
Finding the latest modified file in a directory

Hi,

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);
closedir(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.

Thanks...

Last edited by pradee; 09-01-09 at 02:54.
Reply With Quote
  #2 (permalink)  
Old 10-21-09, 22:56
sco08y sco08y is offline
Registered User
 
Join Date: Oct 2002
Location: Baghdad, Iraq
Posts: 697
Should be $directory\\$file.

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

Code:
%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.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On