Perl File :: Find :: Rule以查找目录中的最新文件

时间:2014-09-17 21:54:46

标签: perl file find rule

我正在尝试获取特定路径($output)下每个目录(针对每个项目)的最新文件列表,不包括单个目录OLD

use strict;
use warnings;
use Data::Dump;
use File::Find::Rule;
my $output = "/abc/def/ghi";
my @exclude_dirs = qw(OLD);
my $rule = File::Find::Rule->new; $rule->or($rule->new
           ->file()
           ->name(@exclude_dirs)
           ->prune
           ->discard,
      $rule->new);
my @files = $rule->in("$output");
dd \@files;

我的目标结构:

My Dir Structure:

/abc/def/ghi
├── project1
│   ├── 2013
|        ├── file1_project1.txt
│   └── 2014
|         ├── foobar__2014_0912_255.txt
|         ├── foobar__2014_0916_248.txt
├── project2
│   ├── 2013
|        ├── file1_project2.txt
│   └── 2014
|         ├── foobarbaz__2014_0912_255.txt
|         ├── foobarbaz__2014_0916_248.txt
└── OLD
    └── foo.txt

当前输出:

/ ABC / DEF / GHI / PROJECT1 /
/ ABC / DEF / GHI / PROJECT1 / 2013
/abc/def/ghi/Project1/2013/file1_project1.txt
/ ABC / DEF / GHI / PROJECT1 / 20l4
/abc/def/ghi/Project1/2014/foobar_2014_0912_255.txt
/abc/def/ghi/Project1/2014/foobar_2014_0916_248.txt
/ ABC / DEF / GHI / Project2的
/ ABC / DEF / GHI / Project2的/ 2013
/abc/def/ghi/Project1/2013/file2_project1.txt
/ ABC / DEF / GHI / Project2的/ 2014
/abc/def/ghi/Project2/2014/foobarbaz_2014_0912_255.txt
/abc/def/ghi/Project2/2014/foobarbaz_2014_0912_248.txt

期望的输出:

/abc/def/ghi/Project1/2014/foobar_2014_0912_255.txt
/abc/def/ghi/Project2/2014/foobarbaz_2014_0912_248.txt

1 个答案:

答案 0 :(得分:1)

File::Find::Rule的以下用法将为您提供完整的文件列表。

您可以构建数组哈希以保存结果,然后筛选出每个项目的最新文件:

use strict;
use warnings;

use Data::Dump;
use File::Find::Rule;

my $basedir      = "testing";
my @exclude_dirs = qw(OLD);

my $rule = File::Find::Rule->new;
$rule->or( $rule->new->directory()->name(@exclude_dirs)->prune->discard, $rule->new )->file;
my @files = $rule->in($basedir);

dd @files;

输出:

(
  "testing/project1/2013/file1_project1.txt",
  "testing/project1/2014/foobar__2014_0912_255.txt",
  "testing/project1/2014/foobar__2014_0916_248.txt",
  "testing/project2/2013/file1_project2.txt",
  "testing/project2/2014/foobarbaz__2014_0912_255.txt",
  "testing/project2/2014/foobarbaz__2014_0916_248.txt",
)

要完成过滤,以下附录使用Path::class

...; # Continued from previous code.

use Path::Class;

my %projects;
for (@files) {
    my $file = file($_);
    my $project = $file->parent->parent;

    $projects{$project} = $file if ! $projects{$project} || $file->stat->mtime > $projects{$project}->stat->mtime;
}

while (my ($project, $file) = each %projects) {
    print "$project - $file\n";
}

输出:

testing/project2 - testing/project2/2014/foobarbaz__2014_0916_248.txt
testing/project1 - testing/project1/2014/foobar__2014_0916_248.txt