infinitloop
infinitloop

Reputation: 3011

Why do I get this "not an array reference" with Perl XML::Simple?

My input xml file is:

<?xml version='1.0'?>
<warnings>
 <IDA>
  <file>filea</file>
  <path>patha</path>
 </IDA>

 <IDA>
  <file>fileaa</file>
  <path>pathaa</path>
 </IDA>

 <IDB>
  <file>fileb</file>
  <path>pathb</path>
 </IDB>

</warnings>

I am reading this file like this:

my @IDs = ("IDA", "IDB");
my $data = $xml->XMLin("xmlfile.xml");
foreach (@IDs)
{
 foreach $id (@{$data->{$_}})
 {
   print $id->{path}."\n";
 }
}

and when I run the script it gives me this error:

Not an ARRAY reference at ./waiver.pl line 18.

(line 18 is the second foreach loop)

EDIT i have duplicated IDA tag.

Upvotes: 3

Views: 3617

Answers (1)

m0skit0
m0skit0

Reputation: 25863

{$data->{$_} is not a valid array reference because you have only one IDA tag, thus no array is built. You can use ForceArray in XMLin to force every tag to be an array even if there's only one.

my $data = $xml->XMLin("xmlfile.xml", ForceArray => 1);

EDIT: now it's giving the error with IDB tag...

Alternatively you can use ref() to check if it's an array or a hash reference:

if (ref({$data->{$_}) eq 'ARRAY')
{
    foreach $id (@{$data->{$_}})
    {
        etc...
    }
}

PS: also may I suggest using keys() function to retreive the keys of the hash instead of having them in a separate array.

Upvotes: 5

Related Questions