FreeKB - Perl (Scripting) XML::Simple Arrays
Perl (Scripting) - XML::Simple Arrays

Let's consider this XML where there are two (or more) identicals keys (name).

  <name role="main">Bugs Bunny</character>
  <name role="support">Elmer Fudd</character>


Data::Dumper can be used to understand how XML::Simple is interpreting the XML.

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 . . .


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";


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 86cb2 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |