2012-12-27 92 views
0

快速提示:我一直被這個問題困住了好幾天,我不一定希望找到答案,但任何可能「啓發」我的幫助。我還想提一提,我是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

+0

1.您可以使用某些東西來初始化'$ path',對吧? 2.爲什麼還要用'readdir'來打算逐個迭代條目呢?如果你把它們全部放入數組中?使用'glob'或者「跳過收集到數組」部分。 3.什麼是失敗? –

回答

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中的核心模塊。

+0

謝謝,這幫了我很多:D – sSmacKk

+0

不客氣。 – TLP