如何在Perl脚本中递归查找文件/文件夹?

gol*_*ean 7 perl module find

我有一个perl脚本,我已经编写,以递归方式搜索我的Windows文件夹中的文件.我输入搜索文本作为perl脚本运行时参数,以查找具有此文本名称的文件.perl脚本如下:

use Cwd;

$file1 = @ARGV[0];    

#@res1 = glob "*test*";
#@res1 = glob "$file1*";
@res1 = map { Cwd::abs_path($_) } glob "$file1*";
foreach (@res1)
{
    print "$_\n";
}
Run Code Online (Sandbox Code Playgroud)

但这并不是递归地搜索所有子目录.我知道glob递归不匹配.
所以尝试使用模块File::Find和功能 find(\&wanted, @directories);

但我得到一个错误说find()未定义.从我从帮助中读到的内容,我认为find()函数是在Perl安装中默认定义的,带有一些基本代码来查找文件夹/文件.不正确吗?

问题是,在上面的perl脚本中,我如何递归搜索文件/文件夹?

第二个问题,我发现perldoc <module> help没有关于在该模块中使用某个函数的示例,这将使其清楚.

您是否可以指出一些好的帮助/文档/书籍,以便使用来自不同perl模块的各种perl函数以及这些模块函数的清晰使用示例.

Bee*_*Bee 15

另一个使用的优秀模块是File :: Find :: Rule,它隐藏了File :: Find的一些复杂性,同时暴露了相同的丰富功能.

use File::Find::Rule;
use Cwd;

my $cwd = getcwd();
my $filelist;

sub buildFileIndex {
    open ($filelist, ">", "filelist.txt") || die $!;

    # File find rule
    my $excludeDirs = File::Find::Rule->directory
                              ->name('demo', 'test', 'sample', '3rdParty') # Provide specific list of directories to *not* scan
                              ->prune          # don't go into it
                              ->discard;       # don't report it

    my $includeFiles = File::Find::Rule->file
                             ->name('*.txt', '*.csv'); # search by file extensions

    my @files = File::Find::Rule->or( $excludeDirs, $includeFiles )
                                ->in($cwd);

    print $filelist map { "$_\n" } @files;
    return \$filelist;
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*dro 7

这两页都是您需要学习的内容:


Col*_*ell 5

另一种方法是使用 find2perl 为您创建脚本的开头。它可以将查找命令变成这样,

find . -type f -name "*test*" -print
Run Code Online (Sandbox Code Playgroud)

到一个等效的 perl 脚本。你只需放置 find2perl 而不是 find 。它在底层使用 File::Find,但可以让您快速上手。


bvr*_*bvr 5

如果您不介意使用 cpan 模块,Path::Class可以为您完成这项工作:

use Path::Class;

my @files;
dir('.')->recurse(callback => sub {
    my $file = shift;
    if($file =~ /some text/) {
        push @files, $file->absolute->stringify;
    }
});

for my $file (@files) {
    # ...
}
Run Code Online (Sandbox Code Playgroud)