【问题标题】:Perl search for specific subdirectory then processPerl搜索特定的子目录然后处理
【发布时间】:2012-07-02 17:25:41
【问题描述】:

所以对于我正在编写的程序,我希望它做的是搜索目录中的所有子目录。如果子目录名称包含一个单词,比如说“foo”,那么程序将打开这个子目录并对子目录中的文件执行一个功能。有人可以帮我解决这个问题吗?它还需要是递归的。提前致谢

【问题讨论】:

  • File::Find 将执行您需要的递归搜索。

标签: perl subdirectory


【解决方案1】:

这可以使用File::Find 模块完成,但我相信Path::Class 更出色,即使它不是核心模块并且可能需要安装。

这个程序找到想要的文件并调用process 来处理它们。目前process 子程序只是打印文件名进行测试。

use strict;
use warnings;

use Path::Class;

my $dir = dir '/path/to/root/directory';

$dir->recurse(callback => sub {
  my $node = shift;
  return if $node->is_dir;
  my $parent = $node->parent;
  if ($parent->basename =~ /foo/) {
    process($node);
  }
});

sub process {
  my $file = shift;
  print $file, "\n";
}

更新

如果您愿意,此程序使用 File::Find 执行相同的任务。

use strict;
use warnings;

use File::Find;
use File::Basename qw/ basename /;

my $dir = '/path/to/root/directory';

find(sub {
  return unless -f;
  if (basename($File::Find::dir) =~ /foo/) {
    process($File::Find::name);
  }
}, $dir);

sub process {
  my $file = shift;
  print $file, "\n";
}

更新

根据要求,这是使用Path::Class::Rule 进行比较的进一步解决方案。正如daxim 建议的那样,代码要短一些。

use strict;
use warnings;

use Path::Class::Rule;

my $rule = Path::Class::Rule->new;
$rule->file->and(sub { $_->parent->basename =~ /foo/ });

my $next = $rule->iter('/path/to/root/directory');
while ( my $file = $next->() ) {
  process($file);
}

sub process {
  my $file = shift;
  print $file, "\n";
}

【讨论】:

  • 您能否也添加一个 Path::Class::Rule 解决方案作为对比?代码应该更短且更具声明性。
  • 好的,如果我无法安装任何模块,我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
相关资源
最近更新 更多