danny0085 has asked for the wisdom of the Perl Monks concerning the following question:

use XML::Simple; my $xml = new XML::Simple; $answers = $xml->XMLin('answers.xml'); $url = $answers->{answer}->[0]->{url}; print "$url";
When I have two or more nodes everything is OK
<?xml version="1.0" encoding="UTF-8"?> <file> <answer> <url>web 1</url> </answer> <answer> <url>web 2</url> </answer> </file>
But When I have only one node I get the error "Not an ARRAY reference at test.pl line 4."
<?xml version="1.0" encoding="UTF-8"?> <file> <answer> <url>web 1</url> </answer> </file>

Replies are listed 'Best First'.
Re: Strange XML error
by runrig (Abbot) on Aug 13, 2012 at 19:28 UTC
    Look at the ForceArray option of XML::Simple. Also follow the previous advice and use Data::Dumper to see what you do have.
      Thank you with forcearray and Dumper resolved the problem
Re: Strange XML error
by xyzzy (Pilgrim) on Aug 13, 2012 at 19:23 UTC

    I don't know anything about this particular module, but the error says very clearly that $answers->{answer} is not an arrayref. This could be because the parser only returns an array of elements when there is more than one element (which would make sense in some cases). Sometimes functions can be forced into returning arrays by using them in list context. Try using Data::Dumper to see exactly what $answers->{answer} is. Read the docs for XML::Simple, they will probably tell you (unless they really suck) what kind of data structure XMLin returns.


    $,=qq.\n.;print q.\/\/____\/.,q./\ \ / / \\.,q.    /_/__.,q..
    Happy, sober, smart: pick two.