PERL - 从目录/子目录/ ..中提取文件的问题?

时间:2012-12-27 14:54:12

标签: perl file recursion directory extract

快速注意:我已经坚持这个问题好几天了,我不一定希望找到答案,但任何可能“启发”我的帮助。我还想提一下,我是Perl的初学者,所以我的知识不是很大,在这种情况下,递归不是我的强项。这里是:

我希望Perl脚本能够做到以下几点:

  • 将目录作为参数
  • 进入已传递的目录及其子目录以查找* .xml文件
  • 将找到的* .xml文件的完整路径存储到数组中。

以下是我到目前为止的代码,但我还没有设法使它工作:

#! /usr/bin/perl -W

my $path;
process_files ($path);

sub process_files
{
    opendir (DIR, $path) or die "Unable to open $path: $!";

    my @files =
        # Third: Prepend the full path
        map { $path . '/' . $_ }
        # Second: take out '.' and '..'
        grep { !/^\.{1,2}$/ }
        # First: get all files
        readdir (DIR);

    closedir (DIR);

    for (@files)
    {
          if (-d $_)
          {            
            push @files, process_files ($_);
          }
          else
          {
             #analyse document
          }
    }
    return @files;
}

有人有任何线索指出我正确的方向吗?或者更简单的方法吗?

谢谢你, sSmacKk:D

1 个答案:

答案 0 :(得分:4)

听起来你应该使用File::Find。其find子例程将以递归方式遍历目录。

use strict;
use warnings;
use File::Find;

my @files;
my $path = shift;
find(
    sub { (-f && /\.xml$/i) or return; 
           push @files, $File::Find::name; 
    }, $path);

子例程将对它找到的文件执行它包含的任何代码。这个简单地将XML文件名(带有完整路径)推送到@files数组。阅读documentation for the File::Find模块中的更多内容,这是perl 5中的核心模块。