我正在尝试使用 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 _;
   }
}

关于perl - Perl文件::查找::规则,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35633820/

10-12 01:22
查看更多