I'm using XML::Simple
in Perl to parse through an XML file and I'm stuck on how to build a loop to go through all the possible elements of an array within the hash.
Here's how to print the 0th element of the array:
print $book_info->{BookList}->{BookData}->{Prices}->{Price}[0]->{is_new};
My terminology might be off when using the words hash vs. array, but I'm trying to loop through all of the elements within {Price}[$ref]
I tried:
my @refs = $book_info->{BookList}->{BookData}->{Prices}->{Price};
foreach(@refs)
{
print $book_info->{BookList}->{BookData}->{Prices}->{Price}[$_]->{store_id};
print "\n";
}
and
foreach my $key (keys (%{$book_info->{BookList}->{BookData}->{Prices}->{Price}}))
{
print $key."\n";
}
This next print statement returns a value of "ARRAY(0x159a57c)"
print [$book_info->{BookList}->{BookData}->{Prices}->{Price}];
foreach (@{$book_info->{BookList}->{BookData}->{Prices}->{Price}}) { print $book_info->{BookList}->{BookData}->{Prices}->{Price}[$_]; #this line is wrong }
Any suggestions? There are multiple {Price}
elements within the {Prices}
element, and each {Price}
element has [x]
attributes in the XML.
People aren't quite getting it right for you. If I understand you correctly, you want:
foreach my $element ( @{ $book_info->{BookList}->{BookData}->{Prices}->{Price} } ) {
print $element->{store_id};
print "\n";
}
Helpful advice for dealing with nested data structures can be found at http://perlmonks.org/?node=References+quick+reference
Marginally extending ysth 's answer:
foreach my $elem_ref (@{$book_info->{BookList}->{BookData}->{Prices}->{Price}})
{
foreach my $key (sort keys %{$elem_ref})
{
print $elem_ref->{$key};
}
print "\n";
}
In part, this uses the recommendation from Perl Best Practices to denote references with the suffix _ref
.
您是否尝试过使用Data :: Dumper转储$ book_info的内容(使用Data :: Dumper; print Dumper($ book_info)?)它应该为您提供有关如何进行操作的线索。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.