【问题标题】:PERL - issues extracting a file from directory/subdirectories/..?PERL - 从目录/子目录/..提取文件时出现问题?
【发布时间】:2012-12-12 22:57:33
【问题描述】:

快速说明:我已经被这个问题困扰了好几天,我不一定希望找到答案,但任何可能“启发”我的帮助。我还想提一下,我是 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.你用一些东西来初始化$path,对吧? 2. 如果您将它们全部塞入数组中,为什么还要使用readdir 来逐个迭代条目?使用glob 或“跳过收集到数组”部分。 3. 到底是什么失败了?

标签: perl file recursion directory extract


【解决方案1】:

听起来您应该使用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 中的核心模块。

【讨论】:

  • 谢谢,这对我帮助很大:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 2021-09-22
  • 2018-04-04
  • 1970-01-01
  • 2011-11-20
  • 2019-11-24
  • 1970-01-01
相关资源
最近更新 更多