user3797544
user3797544

Reputation: 111

Finding newest file in directory

I am trying to build a code that finds the newest file in a directory. I've searched up some solutions but I still cannot get the code to work. I am trying to find the most recent xml file.

#!/usr/bin/perl
use warnings;
use strict;

my $dir_INFO      = '/local/nelly/INFO';
my $dir_InfoNames = '/local/data/InfoNames';

#Open INFO
opendir( DIR, $dir_INFO ) or die "can't opendir INFO";
my @files = grep { !/\./ } readdir(DIR);
foreach my $file (@files) {
    my $dir3 = "/local/nelly/INFO/$file/XML";
    opendir( DIR, $dir3 ) or die "can't opendir XML";
    my @files2 = grep { /.xml/ } readdir(DIR);
    for my $files2 (@files2) {
        open( FILES2, "<", "/local/nelly/INFO/$file/XML/$files2" ) or die "could  not open $files2 \n";
        while (<FILES2>) {
            #sort by modification time
            my %new = map( ( $_, "$dir3\\$_" ), my @xmls );
            @xmls = sort { $new{$a} <=> $new{$b} } @xmls;
            print "$xmls[0]";
            my $locations = $xmls[0];
        }
    }
}

Upvotes: 0

Views: 1425

Answers (3)

NAVEEN PRAKASH
NAVEEN PRAKASH

Reputation: 130

 @Filelist = `ls -t`; $NewestFile = $Filelist[0];

Upvotes: 0

Miller
Miller

Reputation: 35198

Just use File::stat to get the object representation to sort a list of files by mtime.

Note, in order to stat a file, one must provide a system logical reference to it. In other words, a full path might be required. I therefore will often use a file glob to get the list since that will automatically include the path information in the filename.

use strict;
use warnings;

use File::stat;

my @files = sort {stat($a)->mtime <=> stat($b)->mtime} glob('*.pl');

print "Youngest = $files[0]\n";
print "Oldest   = $files[-1]\n";

Upvotes: 1

kzagar
kzagar

Reputation: 355

Are you using Linux, and is it acceptable to use external processes? If so, then you could use this:

# list files in folder with 'ls' command, use '-c' option to sort by creation time
open(F, "ls -ct1 |");
# process lines that get returned one by one
while(<F>) {
    chomp();
    print "$_\n";
}
close(F);

Upvotes: 0

Related Questions