[英]Perl File::Find::Rule
我試圖使用File::Find::Rule
將子文件夾的名稱(非遞歸地)復制到一個數組中。 我也想排除數組@exclude_dirs
中提到的目錄名稱
#!/usr/bin/perl
use strict;
use warnings;
use File::Find::Rule;
use Data::Dumper;
my $basedir = "C:\/Test";
my @exclude_dirs = qw( dir1_excl dir2_excl );
my @subdirs = File::Find::Rule
->directory()
# ->name(@exclude_dirs)->prune->discard, File::Find::Rule->new
->maxdepth(1)
->in( $basedir );
print Dumper(\@subdirs);
$VAR1 = [
'dir1',
'dir2',
'dir3'
]
$VAR1 = [
'C:/Test',
'C:/Test/dir1',
'C:/Test/dir1_excl',
'C:/Test/dir2',
'C:/Test/dir2_excl',
'C:/Test/dir3'
]
您想要的是:
my @subdirs =
File::Find::Rule
->mindepth(1)
->maxdepth(1)
->directory
->or(
File::Find::Rule
->name(@exclude_dirs)
->discard
->prune,
File::Find::Rule
->new
)
->in($basedir);
可能的優化:
my @subdirs =
File::Find::Rule
->mindepth(1)
->maxdepth(1)
->or(
File::Find::Rule
->name(@exclude_dirs)
->discard
->prune,
File::Find::Rule
->directory
)
->in($basedir);
就是說,您所需要的是以下內容:
my @subdirs =
File::Find::Rule
->mindepth(1)
->maxdepth(1)
->not_name(@exclude_dirs)
->directory
->in($basedir);
所有這些都返回完整路徑,因此您需要跟進
s{^\Q$basedir\E/}{} for @subdirs;
通常,我將使用FFR而不是readdir
因為使用readdir
的時間更長,更復雜並且更容易出錯。 但是在這種情況下,這是臨界點。
my @subdirs;
{
my %exclude_dirs = map { $_ => 1 } '.', '..', @exclude_dirs;
opendir(my $dh, $basedir)
or die("Can't read dir \"$basedir\": $!\n");
while (my $fn = readdir($dh)) {
next if $exclude_dirs{$fn};
my $qfn = "$basedir/$fn";
if (!stat($qfn)) {
warn("Skipping \$qfn\": Can't stat: $!\n");
next;
}
push @subdirs, $fn if -d _;
}
}
use strict;
use warnings;
use Data::Dumper;
my $basedir = "C:/Test";
my @exclude_dirs = qw(. .. dir1_excl dir2_excl);
my $exclude_pat = join('|', map { quotemeta } @exclude_dirs);
opendir(my $dh, $basedir) or die $!;
my @subdirs = grep { -d "$basedir/$_" && !/^(?:$exclude_pat)\z/i } readdir($dh);
closedir($dh);
print Dumper(\@subdirs);
如果要排除的目錄不像您在問題中所顯示的那樣動態,則無需在運行時構建正則表達式:
my @subdirs = grep { -d "$basedir/$_" && !/^(?:\.|\.\.|dir1_excl|dir2_excl)\z/i } readdir($dh);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.