我想在perl脚本中复制ls -ltr unix命令,而不使用反引号,exec或系统.以下脚本正在运行:
use strict;
my $dir="/abc/xyz/log";
opendir(DIR, $dir) or die "Can not open $dir $!";
my @latest = (sort {-M $b <=> -M $a} <$dir/*>);
my @latest2= grep { !/^\./ && -f "$_"} @latest;
closedir DIR;
Run Code Online (Sandbox Code Playgroud)
问题:如何将sort和grep组合在一行中,以便我可以取消@ latest2?
rub*_*ots 10
这里介绍的解决方案已经可以,但如果在一个非常大的目录上使用,可能会变慢,然后sort函数会反复对相同的文件重复应用-M.因此,可以使用Schwartzian变换来避免这种情况(如有必要):
...
my @sorted_fnames =
map $_->[0] , # ? extract file names
sort { $a->[1] <=> $b->[1] } # ? sort ascending after mdate
map [$_, -M $_] , # ? pre-build list for sorting
grep ! /^\.\.?$/ , # ? extract file names except ./..
readdir $dirhandle; # ? read directory entries
...
Run Code Online (Sandbox Code Playgroud)
问候
RBO