I'm a bit confused from File::Find documentation... What is the equivalent to $ find my_dir -maxdepth 2 -name "*.txt"?
jus*_*ime 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);
Run Code Online (Sandbox Code Playgroud)
或者创建一个迭代器:
my $ffr_obj = File::Find::Rule->file()
->name("*.txt")
->maxdepth($level)
->start($dir);
while (my $file = $ffr_obj->match())
{
print "$file\n"
}
Run Code Online (Sandbox Code Playgroud)
我想我只是使用一个,glob因为你真的不需要所有目录遍历的东西:
my @files = glob( '*.txt */*.txt' );
Run Code Online (Sandbox Code Playgroud)
我创建了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->();
Run Code Online (Sandbox Code Playgroud)
通常,您可以将find(1)命令转换为Perl程序find2perl(在v5.20中删除但在CPAN上删除):
% find2perl my_dir -d 2 -name "*.txt"
Run Code Online (Sandbox Code Playgroud)
但显然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");
}
Run Code Online (Sandbox Code Playgroud)
现在你已经开始编程,你可以插入你需要的任何其他东西,包括preprocess修剪树的步骤.
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" ;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32741 次 |
| 最近记录: |