perl, parsing XML using XML::Simple

无人久伴 提交于 2019-12-11 03:34:44

问题


I'm doing something wrong when parsing XML. Somehow I has to iterate two loops, where only one should be needed. What am I doing wrong here?

First the xml data:

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

Then my perl code:

#!/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");
}

And finally the response (which is fine)

$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.

回答1:


You create an array with one element (a reference to an array) with

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

Then you iterate over the elements of that array with

foreach my $fish (@fishes)

That's just a really weird way of doing

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

Let's use that, but rename $fish to $fishes, and $innerFish to $fish.

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

Don't forget to use the ForceArray => [qw( fish )] option to make sure the code works when you only have a single fish.




回答2:


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



来源:https://stackoverflow.com/questions/15084154/perl-parsing-xml-using-xmlsimple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!