2012-06-08 29 views
1

我想解析位於一個目錄的子目錄中的特定XML文件。出於某種原因,我收到錯誤說文件不存在。如果文件不存在,它應該轉到下一個子目錄。更改目錄並獲取xml文件以解析perl中的某些數據

這裏是我的代碼

 use strict; 
     use warnings; 
     use Data::Dumper; 
     use XML::Simple; 

     my @xmlsearch = map { chomp; $_ } `ls`; 

     foreach my $directory (@xmlsearch) { 
      print "$directory \n"; 
      chdir($directory) or die "Couldn't change to [$directory]: $!"; 
      my @findResults = `find -name education.xml`; 

     foreach my $educationresults (@findResults){ 
      print $educationresults; 
      my $parser = new XML::Simple; 
      my $data = $parser->XMLin($educationresults); 
      print Dumper($data); 
      chdir('..');   
     } 

     } 

     ERROR 
     music/gitar/education.xml 
     File does not exist: ./music/gitar/education.xml 
+0

爲什麼不使用['使用File :: Find;'](http://perldoc.perl.org/File/Find.html)? – 2012-06-08 15:25:14

+0

您是否想要遞歸查找'education.xml'文件,還是僅查找這些目錄? – TLP

+0

你好,我只是想找到一個教育目錄到一個目錄。所以主目錄是音樂,可以說10個子目錄。例如吉他,鋼琴,鼓。我只想在音樂/吉他或音樂/鋼琴下搜索。我不想在音樂/吉他/ dir1/dir2下搜索。 – Maxyie

回答

1

使用chdir你做的方式使代碼IMO的可讀性。您可以使用File::Find那個:

use autodie; 
use File::Find; 
use XML::Simple; 
use Data::Dumper; 

sub findxml { 
    my @found; 

    opendir(DIR, '.'); 
    my @where = grep { -d && m#^[^.]+$# } readdir(DIR); 
    closedir(DIR); 

    File::Find::find({wanted => sub { 
     push @found, $File::Find::name if m#^education\.xml$#s && -f _; 
    } }, @where); 
    return @found; 
} 

foreach my $xml (findxml()){ 
    say $xml; 
    print Dumper XMLin($xml); 
} 
0

當你發現自己依靠反引號執行shell命令,你應該考慮是否有perl正確的方式去做。在這種情況下,有。

ls可以替換爲<*>,這是一個簡單的glob。行:

my @array = map { chomp; $_ } `ls`; 

是說

chomp(my @array = `ls`); # chomp takes list arguments as well 

但當然,正確的方法是

my @array = <*>; # no chomp required 

現在只是一個迂迴的方式,簡單的解決方案,這一切僅僅是爲了做

for my $xml (<*/education.xml>) { # find the xml files in dir 1 level up 

其中將覆蓋一級目錄,不帶遞歸。對於全遞歸,使用File::Find

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

my @list; 
find(sub { push @list, $File::Find::name if /^education\.xml$/i; }, "."); 

for (@list) { 
    # do stuff 
    # @list contains full path names of education.xml files found in subdirs 
    # e.g. ./music/gitar/education.xml 
} 

你應該注意到,改變目錄不是必需的,在我的經驗,不值得的麻煩。而不是做的:

chdir($somedir); 
my $data = XMLin($somefile); 
chdir(".."); 

簡單地做:

my $data = XMLin("$somedir/$somefile"); 
+0

嘿謝謝你的回答,它有助於回溯到只有一個子目錄。 :) – Maxyie

相關問題