使用Perl的File :: Find时,可以快速找到&限制搜索深度的简便方法? [英] When using Perl's File::Find what's a quick & easy way to limit search depth?

查看:91
本文介绍了使用Perl的File :: Find时,可以快速找到&限制搜索深度的简便方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将Perl的 File :: Find 限制到指定目录的目录深度(在指定搜索之下) 1&在它下面的2个子目录。

I want to be able to limit Perl's File::Find to a directory depth (below the specified search) to the specified directory and 1 & 2 subdirectories beneath it.

如果可能的话,我希望能够同时枚举文件。

I want to be able to enumerate the files at the same time, if this is possible.

它必须使用绝对路径。

推荐答案

perlmonks节点解释了如何从GNU的发现中实现最小深度和最大深度。

This perlmonks node explains how to implement mindepth and maxdepth from GNU's find.

基本上,它们计算目录中的斜杠数量,并以此来确定深度。然后,预处理函数将仅返回深度小于max_depth的值

Basically, they count the number of slashes in a directory, and use that to determine the depth. The preprocess function will then only return the values where the depth is smaller than the 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的File :: Find时,可以快速找到&amp;限制搜索深度的简便方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆