简体   繁体   中英

Accessing xml data using perl XML::Simple

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?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM