解析 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.