这个问题是“在perl中,查找给定时间间隔内修改的文件的最简单方法是什么?”的特例。下面的解决方案可以很容易地推广。在 bash 中,我们可以输入
> find . -mtime -1h
Run Code Online (Sandbox Code Playgroud)
但我想用纯 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";
Run Code Online (Sandbox Code Playgroud)
use File::Find::Rule qw( );
my $cutoff = time - 60*60;
say for File::Find::Rule->mtime( ">=$cutoff" )->in( "." );
Run Code Online (Sandbox Code Playgroud)