dais has asked for the wisdom of the Perl Monks concerning the following question:

hi, I want to get the latest file in a Directory by providing the starting characters of a file name. With this code, I am able to get the file based on the name.But it will start searching files in dirctory based on file names(will search for the files based on file name sorted in ascending order).So if timestamp is there in 2 macthing file, i will get the earlier file as filename is smaller for that. i need to get the file serach to be done based on the updated timestamp of the files in the directoy.Please help.
#!/usr/bin/perl use Getopt::Std; use File::Find; getopts('i:'); $file_serch= $opt_i; $dir = "/MYDIR/"; find(\&edits, $dir); sub edits() { $pos = rindex $File::Find::name,'/'; $file_name = substr($File::Find::name,$pos+1,length($File::Find::n +ame)); $in_file = $file_name if ($file_name=~ m/^$file_serch/); exit if $in_file ne ""; }

Replies are listed 'Best First'.
Re: Get latest file based on name
by Corion (Patriarch) on Aug 16, 2010 at 12:48 UTC

    I enforce that all file names in interfaces are ascii-sortable, by making people name them in a schema like $file-yyyymmdd-hhmmss . This makes it fairly trivial to sort them and extract the first or latest file:</c>

    my($first) = (sort @files)[0]; my($last) = (sort @files)[-1];

    If your files are not named in a sane way (for example German dates are of the form dd.mm.yyyy), you will have to look at sort on how to sort by arbitrary values.

    From looking at your code, you might be interested in glob. Also, I often use a regular expression to get at the filename part:

    my $file = "/some/file/name.txt"; my $filename; if ($file =~ m!(?:.*/)?([^/])$!) { $filename = $1; } else { die "Weird file name format: '$filename'"; }; print "Got $filename";
Re: Get latest file based on name
by dasgar (Priest) on Aug 16, 2010 at 15:57 UTC

    First, a quick tip. If you can use <c></c> around your code, it will make it much easier for others to read it. To illustrate the difference, Corion's response to your post is using those tags.

    If I read your post correctly, you're wanting to do the following:

    • Find all files within a specified directory that whose file name starts with a user specified string
    • Of those files that were found, return just the file that has the latest last modified (updated) time stamp

    Based on that assumption, here's the general method that I would take to do that task (without being concerned with efficiency):

    • Use File::Find to find the list of files in the specified directory with the file name requirements
    • Loop through that list and use either stat or File::stat to determine which file has the latest modified date.

    This might not be the most efficient method of doing it, but it would be approach that I personally would start off with.