2

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

2 回答 2

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 )]选项来确保代码有效。

于 2013-02-26T08:13:16.250 回答
0

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

于 2013-02-26T08:16:11.793 回答