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

Updated:   |  Perl (Scripting) articles

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


Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee


Add a Comment

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