在Perl中有没有一种很好的方法可以在目录中找到最新的文件(根据修改日期最新)?
到目前为止,我所做的是搜索我需要的文件,对于每个文件,获取它的修改时间,将其放入一个包含文件名和修改时间的数组中,然后对其进行排序。
一定有更好的办法。
发布于 2008-11-30 17:26:00
你不需要把所有的修改时间和文件名都保存在一个列表中,你可能也不应该这样做。你只需要查看一个文件,看看它是否比你之前看到的最旧的文件更旧:
{
opendir my $dh, $dir or die "Could not open $dir: $!";
my( $newest_name, $newest_time ) = ( undef, 2**31 -1 );
while( defined( my $file = readdir( $dh ) ) ) {
my $path = File::Spec->catfile( $dir, $file );
next if -d $path; # skip directories, or anything else you like
( $newest_name, $newest_time ) = ( $file, -M _ ) if( -M $path < $newest_time );
}
print "Newest file is $newest_name\n";
}
发布于 2008-11-30 09:51:37
您可以尝试使用外壳的ls
命令:
@list = `ls -t`;
$newest = $list[0];
发布于 2008-11-30 09:52:25
假设您知道要查找的$DIR
:
opendir(my $DH, $DIR) or die "Error opening $DIR: $!";
my %files = map { $_ => (stat("$DIR/$_"))[9] } grep(! /^\.\.?$/, readdir($DH));
closedir($DH);
my @sorted_files = sort { $files{$b} <=> $files{$a} } (keys %files);
# $sorted_files[0] is the most-recently modified. If it isn't the actual
# file-of-interest, you can iterate through @sorted_files until you find
# the interesting file(s).
包装readdir
的grep
会过滤掉".“和"..“UNIX(-ish)文件系统中的特殊文件。
https://stackoverflow.com/questions/328673
复制相似问题