如何在目录中找到最新创建的文件? [英] How can I find the newest created file in a directory?
问题描述
Perl中是否有一种优雅的方法来查找目录中的最新文件(按修改日期最新)?
Is there an elegant way in Perl to find the newest file in a directory (newest by modification date)?
到目前为止,我正在搜索所需的文件,对于每个文件,它都是修改时间,将其推入一个包含文件名,修改时间的数组,然后对其进行排序.
What I have so far is searching for the files I need, and for each one get it's modification time, push into an array containing the filename, modification time, then sort it.
必须有更好的方法.
推荐答案
如果您需要排序列表,则您的方式是正确"的方式(不仅是第一种,请参阅Brian的答案).如果您不想自己编写该代码,请使用这个
Your way is the "right" way if you need a sorted list (and not just the first, see Brian's answer for that). If you don't fancy writing that code yourself, use this
use File::DirList;
my @list = File::DirList::list('.', 'M');
就我个人而言,我不会使用ls -t
方法-该方法涉及派生另一个程序,并且该程序不可移植.简直就是我所说的优雅"!
Personally I wouldn't go with the ls -t
method - that involves forking another program and it's not portable. Hardly what I'd call "elegant"!
关于rjray的解决方案手动编码的解决方案,我会稍作更改:
Regarding rjray's solution hand coded solution, I'd change it slightly:
opendir(my $DH, $DIR) or die "Error opening $DIR: $!";
my @files = map { [ stat "$DIR/$_", $_ ] } grep(! /^\.\.?$/, readdir($DH));
closedir($DH);
sub rev_by_date { $b->[9] <=> $a->[9] }
my @sorted_files = sort rev_by_date @files;
此后,@sorted_files
包含排序列表,其中第0个元素是最新文件,每个元素本身包含对stat
结果的引用,文件名本身位于最后一个元素中:
After this, @sorted_files
contains the sorted list, where the 0th element is the newest file, and each element itself contains a reference to the results of stat
, with the filename itself in the last element:
my @newest = @{$sorted_files[0]};
my $name = pop(@newest);
这样做的好处是,如果需要,以后可以更轻松地更改排序方法.
The advantage of this is that it's easier to change the sorting method later, if desired.
这是目录扫描的易于阅读(但更长)的版本,它还确保仅将纯文件添加到列表中:
here's an easier-to-read (but longer) version of the directory scan, which also ensures that only plain files are added to the listing:
my @files;
opendir(my $DH, $DIR) or die "Error opening $DIR: $!";
while (defined (my $file = readdir($DH))) {
my $path = $DIR . '/' . $file;
next unless (-f $path); # ignore non-files - automatically does . and ..
push(@files, [ stat(_), $path ]); # re-uses the stat results from '-f'
}
closedir($DH);
NB:对defined()
进行的readdir()
结果测试是因为如果仅测试if (my $file = readdir($DH))
NB: the test for defined()
on the result of readdir()
is because a file called '0' would cause the loop to fail if you only test for if (my $file = readdir($DH))
这篇关于如何在目录中找到最新创建的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!