2013-02-26 182 views
2

解析XML時我做錯了什麼。 不知何故,我必須迭代兩個循環,其中只需要一個循環。我在這裏做錯了什麼?perl,使用XML解析XML ::簡單

首先XML數據:

<fishy> 
    <fish displayName   = "Scalar" 
     description   = "the first fish I bought." 
    /> 
    <fish displayName   = "crystal red" 
     description   = "not really a fish." 
    /> 
</fishy> 

然後我的Perl代碼:

#!/usr/bin/perl -w 
use strict; 
use XML::Simple; 
use Data::Dumper; 

#Read configuration 
my $simple = XML::Simple->new(); 
my $data = $simple->XMLin('test.xml'); 
print Dumper($data) . "\n"; 


my @fishes = $data->{fish}; 

#This is weird.. Why do we have nested arrays? 
foreach my $fish (@fishes) 
{ 
    foreach my $innerFish (@{$fish}) 
    { 
    print ("\n" . $innerFish->{displayName} . " is " . $innerFish->{description}); 
    } 
    print ("\n"); 
} 

最後的反應(這是罰款)

$VAR1 = { 
      'fish' => [ 
        { 
         'description' => 'the first fish I bought.', 
         'displayName' => 'Scalar' 
        }, 
        { 
         'description' => 'not really a fish.', 
         'displayName' => 'crystal red' 
        } 
        ] 
     }; 


Scalar is the first fish I bought. 
crystal red is not really a fish. 
+0

如果沒有,會發生什麼? – 2013-02-26 08:07:35

回答

4

您創建一個數組元素(對數組的引用)與

my @fishes = $data->{fish}; 

然後你遍歷數組中的元素與

foreach my $fish (@fishes) 

這只是一個做

my $fish = $data->{fish}; 

讓我們使用,但重命名$fish$fishes真正奇怪的方式,並$innerFish$fish

my $fishes = $data->{fish}; 
for my $fish (@$fishes) { 
    print($fish->{displayName}, " is ", $fish->{description}, "\n"); 
} 

不要忘記使用ForceArray => [qw(fish)]選項,以確保代碼工作時,你只有一條魚。

+0

謝謝ikegami – daljian 2013-02-26 08:24:11

0

my @fishes = @{$data->{fish}};

+1

ug,不需要的數組副本。這是一個完全的浪費。 – ikegami 2013-02-26 08:16:59