我希望能够限制 Perl 的 File::Find
到一个目录深度(低于指定搜索)到指定目录和 它下面的 1 和 2 个子目录。
如果可能的话,我希望能够同时枚举文件。
它必须使用绝对路径。
最佳答案
此 perlmonks node解释了如何从 GNU 的 find 实现 mindepth 和 maxdepth。
基本上,他们计算目录中斜杠的数量,并使用它来确定深度。 preprocess函数将只返回深度小于 max_depth 的值。
my ($min_depth, $max_depth) = (2,3);
find( {
preprocess => \&preprocess,
wanted => \&wanted,
}, @dirs);
sub preprocess {
my $depth = $File::Find::dir =~ tr[/][];
return @_ if $depth < $max_depth;
return grep { not -d } @_ if $depth == $max_depth;
return;
}
sub wanted {
my $depth = $File::Find::dir =~ tr[/][];
return if $depth < $min_depth;
print;
}
根据您的情况量身定制:
use File::Find;
my $max_depth = 2;
find( {
preprocess => \&preprocess,
wanted => \&wanted,
}, '.');
sub preprocess {
my $depth = $File::Find::dir =~ tr[/][];
return @_ if $depth < $max_depth;
return grep { not -d } @_ if $depth == $max_depth;
return;
}
sub wanted {
print $_ . "\n" if -f; #Only files
}
关于perl - 当使用 Perl 的 File::Find 时,限制搜索深度的快速简便方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9919909/