#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use File::Find;
use File::stat;
use Carp;
my $files_path = "/tmp/files/";
my %files;
sub files_wanted {
if (/\.tgz$/) {
my $current_file_mtime = stat($File::Find::name)->mtime or croak "Error, could not stat file $File::Find::name";
$files{$current_file_mtime} = $File::Find::name;
};
}
find( \&files_wanted ,$files_path);
print '%files:' . "\n" . Dumper(\%files);
my @sorted_files_mtimes = reverse sort keys %files;
print "sorted_files_mtimes=$sorted_files_mtimes[0]\n";
my $newest_file = $files{$sorted_files_mtimes[0]};
print "$newest_file\n";
Refactorings
No refactoring yet !
bob
January 7, 2009, January 07, 2009 09:17, permalink
untested
use strict;
use warnings;
use Data::Dumper;
use File::Find;
my $files_path = "/tmp/files/";
my @files; # array of filenames
sub files_wanted {
if (/\.tgz$/) {
push @files, $File::Find::name;
}
}
find( \&files_wanted ,$files_path);
print '@files:', "\n", Dumper(\@files);
# Schwartzian transform
my @sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] } # use numerical comparison "<=>"
map { [$_, -M $_] } # "-M" finds time since modification time, in days; this is ordered opposite from modification time itself
@files;
my $newest_file = $sorted[0];
print "$newest_file\n";
bonzobo.blogspot.com
January 7, 2009, January 07, 2009 14:36, permalink
Refactored the code so that it doesn't save all the files in a hash, instead it keeps a record of the highest mtime, and the file name with the highest mtime. This saves memory as we don't have to keep the whole file list in memory, and no need to sort in the end.
Changed print function to "say" function.
Extracted the find_file_regex_pattern to a variable.
#!/usr/bin/perl
use strict;
use warnings;
use feature qw(say);
use Data::Dumper;
use File::Find;
use File::stat;
use Carp;
if (!$ARGV[0]) {
say "Usage: $0 directory_to_search";
say "Example: $0 /tmp/";
}
my $files_path = $ARGV[0];
my $find_file_regex_pattern = '\.tgz$';
my $highest_mtime_found = 0;
my $highest_mtime_file_name;
sub files_wanted {
if (m/$find_file_regex_pattern/) {
my $current_file_mtime = stat($File::Find::name)->mtime
or croak "Error, could not stat file $File::Find::name";
if ($highest_mtime_found <= $current_file_mtime) {
$highest_mtime_found = $current_file_mtime;
$highest_mtime_file_name = $File::Find::name;
}
};
}
find( \&files_wanted ,$files_path);
if ($highest_mtime_found == 0) {
say "Could not find any file with: $find_file_regex_pattern";
exit(1);
}
my $newest_file = $highest_mtime_file_name;
say "Found the file with the highest mtime: $newest_file";
exit(0);
Here's a small script that looks in a certain directory for files with a spesific extention, and returns the file with the highest mtime.
Currently, a hash is created with the mtime as keys and filenames as values. So if 2 or more files have the same mtime, each will be inserted into the hash, overwriting one another and only the last will remain in the hash.