0

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?

simbabque
  • 53,749
  • 8
  • 73
  • 136
user3871995
  • 983
  • 1
  • 10
  • 19
  • 3
    Just in case you haven't been beaten over the head with this yet: [Why is XML::Simple “Discouraged”?](http://stackoverflow.com/q/33267765/176646) – ThisSuitIsBlackNot Oct 25 '16 at 15:33
  • I am not sure what the typo is you made when transcribing your code here. This is **not** the code that produces this error message. I can't reproduce it either. Anyway, the right syntax is pretty clear. – simbabque Oct 25 '16 at 15:43

1 Answers1

4

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
Grant McLean
  • 6,898
  • 1
  • 21
  • 37
simbabque
  • 53,749
  • 8
  • 73
  • 136