這個問題是“在perl中,查找在給定時間間隔內修改的檔案的最簡單方法是什么?”的特例。下面的解決方案可以很容易地推廣。在 bash 中,我們可以輸入
> find . -mtime -1h
但我想在純 perl 中做到這一點。下面的代碼就是這樣做的。它明確地stat在每個檔案上運行。
有什么方法可以使這更簡單或更優雅?當然,這比 bash 命令慢;我不是想與 bash 競爭效率。我只是想純粹用 perl 來做。
#!/usr/bin/env perl
use strict; use warnings;
use File::Find;
my $invocation_seconds=time;
my $interval_left = $invocation_seconds - (60 * 60); # one hour ago
my $count_all=0;
my @selected;
find(
sub
{
$count_all ;
my $mtime_seconds=(stat($_))[9];
return unless defined $mtime_seconds; # if we edit files while running current script, this can be undef on occasion
return unless ($mtime_seconds>$interval_left);
push@selected,$File::Find::name;
}
,
'.', # current directory
);
my $end_seconds=time;
my $totalselected=scalar@selected;
print ($_,"\n",)for@selected;
print $^V; print " <- perl version\n";
print 'selected ',$totalselected, '/',$count_all,' in ',($end_seconds-$invocation_seconds),' seconds',"\n";
uj5u.com熱心網友回復:
use File::Find::Rule qw( );
my $cutoff = time - 60*60;
say for File::Find::Rule->mtime( ">=$cutoff" )->in( "." );
uj5u.com熱心網友回復:
以下演示示例代碼利用函式stat過濾掉最近一小時修改過的檔案。
注:代碼稍作修改即可采用遞回
use strict;
use warnings;
use feature 'say';
use constant STAMP => time() - 60*60;
use constant MTIME => 9;
my $dir = shift || '.';
my @files;
(stat($_))[MTIME] > STAMP && push @files, $_
for glob("$dir/*");
say "
Files changes in last hour
--------------------------";
say for @files;
報告查找時間的遞回版本
use strict;
use warnings;
use feature 'say';
use Time::HiRes qw(gettimeofday tv_interval);
use constant STAMP => time() - 60*60;
use constant MTIME => 9;
my $dir = shift || '.';
my $start = [gettimeofday];
my $found = lookup($dir);
my $elapsed = tv_interval($start)
say "
Elapsed lookup time: $elapsed seconds";
say "
Files changed in last hour
--------------------------";
say for @$found;
exit 0;
sub lookup {
my $dir = shift;
my $files;
for my $item ( glob("$dir/*") ) {
if( -d $item ) {
my $matched = lookup($item);
push @$files, $_ for @{$matched};
}
next unless (stat($item))[MTIME] > STAMP;
push @$files, $item if -f $item;
}
return $files;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/386129.html
