Reputation: 1213
I have some xml data, the dump looks like this:
$VAR1 = {
'Members' => [
{
'Age' => '19',
'Name' => 'Bob'
},
{
'Age' => '18',
'Name' => 'Jane'
},
{
'Age' => '21',
'Name' => 'Pat'
},
{
'Age' => '22',
'Name' => 'June'
}
],
'Sports' => [
{
'Players' => '20',
'Name' => 'Tennis'
},
{
'Players' => '35',
'Name' => 'Basketball'
}
],
};
I have tried the following code to print out the data:
foreach my $member (@($xml->{Members})) {
print("Age: $xml->{Age}");
}
But keep getting errors like:
Can't use string ("4") as a HASH ref while "strict refs" in use
Any idea why this won't work?
Upvotes: 0
Views: 58
Reputation: 54323
You are using the wrong syntax.
# here ... and here
# V V
foreach my $member (@($xml->{Members})) { ... }
To dereference, you need curly braces {}
, not parenthesis ()
.
Once you've fixed that (which I think was a typo in the question, not in your real code), you have:
foreach my $member ( @{ $xml->{Members} } ) {
print "Age: $xml->{Age}";
}
But that's still wrong. You want to access the $member
, not the whole $xml
structure, because that doesn't have an Age
, does it?
foreach my $member ( @{ $xml->{Members} } ) {
print "Age: $member->{Age}\n";
}
That will give you
Age: 19
Age: 18
Age: 21
Age: 22
Upvotes: 4