Perl (Scripting) - XML::Simple Arrays

by
Jeremy Canfield |
Updated: March 09 2020
| Perl (Scripting) articles
Let's consider this XML where there are two (or more) identicals keys (name).
<acme>
<name role="main">Bugs Bunny</character>
<name role="support">Elmer Fudd</character>
</acme>
Data::Dumper can be used to understand how XML::Simple is interpreting the XML.
#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;
my $xml= XMLin("example.xml");
print Dumper $xml;
Which will produce the following.
- Data inside of { } is interpreted as a hash
- Data inside of [ ] is interpreted as an array
- "name" is the root key
- "content" and "role" are child keys in an array below the root key
- "Bugs Bunny" and "Elmer Fudd" are values of the "content" key
- "main" and "support" are values of the "role" key
$VAR1 = {
'name' => [
{
'content' => 'Bugs Bunny',
'role' => 'main'
},
'content' => 'Elmer Fudd',
'role' => 'support'
}
]
};
The following . . .
#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
my $xml = XMLin("example.xml");
print $xml->{'name'}->{'content'};
. . . will return this output.
Not a HASH reference
This is because the XML contains an array. In the following, . . .
print $xml->{'name'}->[0]->{'content'};
print $xml->{'name'}->[1]->{'content'};
[0] will return "Bugs Bunny" and [1] will return "Elmer Fudd".
Bugs Bunny
Elmer Fudd
Or you can loop through the <name> key, which will cause $key variable to contain [0] and [1]. The following will also return both "Bugs Bunny" and "Elmer Fudd".
foreach my $key ( keys @{$xml->{'name'}} ) {
print "$xml->{'name'}->[$key]->{'content'}\n";
}
Did you find this article helpful?
If so, consider buying me a coffee over at