perl - 当使用 Perl 的 File::Find 时,限制搜索深度的快速简便方法是什么?

标签 perl directory depth file-find

我希望能够限制 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/

相关文章:

algorithm - 决策树中叶子的最短可能深度(比较排序算法)

perl - 在 Perl 中从 HTTP 请求中提取 header

arrays - 旧版本的 Perl 有不同的数组索引规则吗?

regex - perl grep 10 行日志

perl - XML::Dumper 在输出中使用错误的哈希引用

c - c 中的二叉树 -> 在深度超过 7 时崩溃

linux - 堆叠 linux 文件夹内容以显示为一个文件夹

unix - Cmake 无法工作 - 没有当前工作目录

directory - WGet 镜像而不将其放在子目录(即 domain.com)中

list - 使用(受限)Racket 查找列表的深度