PERL-从目录/子目录/提取文件时出现问题.



快速提示:我已经被这个问题困扰了好几天了,我不一定希望找到答案,但任何可能"启发"我的帮助。我还想说的是,我是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

听起来应该使用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数组上。在File::Find模块的文档中阅读更多信息,它是perl5中的核心模块。

最新更新