Perl File :: Find :: Rule

时间:2016-02-25 17:10:14

标签: 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'
        ]

2 个答案:

答案 0 :(得分:4)

你想要的是什么:

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 _;
   }
}

答案 1 :(得分:2)

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);