Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: How to find the most recent file?

by shmem (Chancellor)
on Jan 09, 2010 at 20:15 UTC ( [id://816536]=note: print w/replies, xml ) Need Help??


in reply to How to find the most recent file?

Here's a simple trick, though perl, not PC:

#!/usr/bin/perl use File::Find; use Getopt::Std; use Cwd; use strict; my $u = "usage: $0 -n count -s skip-pattern dir [dir ...]\n" . " where count is number of newest files to report\n" . " and skip-pattern is a comma separated list of regexes\n" . " to apply upon files found, which will be - skipped\n"; die $u unless @ARGV; my %o; getopt('ns',\%o); my $p; my $s; if($o{s}) { ($p=$o{s}) =~ s/,/\|/g; $s++; } my $n = $o{n} ? $o{n} - 1 : 10; # default 10 files my @d = @ARGV; push @d, getcwd unless @d; my @f; $#f = $n; # preallocate $n elements ! -d $_ and warn "directory $_: $!\n" and undef $_ for @d; @d = grep { defined $_ } @d; @d or die "no searchable directories in argument list\n"; find(\&wanted, @d); print "skip-pattern: ($p)\n" if $o{s}; print join("\n", map { scalar(localtime $_->[0]).' '.$_->[1] } @f ),"\n"; sub wanted { my $file = $File::Find::name; -d && return; $s and $file =~/($p)/ and return; my $time = (stat)[9] or die "can't stat $file: $!\n"; # mtime # if file is newer or as new than the first file... if ($f[0]->[0] < $time) { unshift @f,[$time,$file]; pop @f if $#f > $n; return; } # ...else insert the found file in the list. for( my $i = 0; $i<= $#f; $i++) { if($time >= $f[$i]->[0]) { die unless $time; splice @f,$i,0,[$time, $file]; pop @f if $#f > $n; return; } } }

update: improved code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://816536]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-03-29 16:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found