如何在Perl中使用File :: Find?

时间:2010-09-25 20:38:07

标签: perl find

我对File::Find文档感到有点困惑......等同于$ find my_dir -maxdepth 2 -name "*.txt"的是什么?

4 个答案:

答案 0 :(得分:31)

就个人而言,我更喜欢File::Find::Rule,因为这不需要你创建回调例程。

use strict;
use Data::Dumper;
use File::Find::Rule;

my $dir = shift;
my $level = shift // 2;

my @files = File::Find::Rule->file()
                            ->name("*.txt")
                            ->maxdepth($level)
                            ->in($dir);

print Dumper(\@files);

或者创建一个迭代器:

my $ffr_obj = File::Find::Rule->file()
                              ->name("*.txt")
                              ->maxdepth($level)
                              ->start($dir);

while (my $file = $ffr_obj->match())
{
    print "$file\n"
}

答案 1 :(得分:7)

我想我只使用glob,因为你真的不需要所有的目录遍历:

 my @files = glob( '*.txt */*.txt' );

我制作了File::Find::Closures,以便您轻松创建传递给find的回调:

 use File::Find::Closures qw( find_by_regex );
 use File::Find qw( find );

 my( $wanted, $reporter ) = File::Find::Closures::find_by_regex( qr/\.txt\z/ );

 find( $wanted, @dirs );

 my @files = $reporter->();

通常,您可以将find(1)命令转换为带find2perl的Perl程序(在v5.20中删除,但在CPAN中删除):

% find2perl my_dir -d 2  -name "*.txt"

但显然find2perl不理解-maxdepth,所以你可以放弃它:

% find2perl my_dir -name "*.txt"
#! /usr/local/perls/perl-5.13.5/bin/perl5.13.5 -w
    eval 'exec /usr/local/perls/perl-5.13.5/bin/perl5.13.5 -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell

use strict;
use File::Find ();

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

sub wanted;



# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, 'my_dir');
exit;


sub wanted {
    /^.*\.txt\z/s
    && print("$name\n");
}

现在您已经开始编程,您可以插入所需的任何其他内容,包括修剪树的preprocess步骤。

答案 2 :(得分:6)

use File::Find ; 
use Cwd ; 

my $currentWorkingDir = getcwd;

my @filesToRun = ();
my $filePattern = '*.cmd' ; 
#add only files of type filePattern recursively from the $currentWorkingDir
find( sub { push @filesToRun, $File::Find::name  
                                    if ( m/^(.*)$filePattern$/ ) }, $currentWorkingDir) ;

foreach  my $file ( @filesToRun  ) 
{
    print "$file\n" ;   
} 

答案 3 :(得分:2)

还有方便的find2perl实用程序。使用它代替Unix find命令,使用与'find'相同的命令行参数,它将生成使用File :: Find的相应Perl代码。

$ find2perl my_dir -maxdepth 2 -name "*.txt"