Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Strange XML error

by danny0085 (Sexton)
on Aug 13, 2012 at 19:06 UTC ( #987183=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://987183]
Approved by blue_cowdawg
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2021-05-13 09:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (134 votes). Check out past polls.

    Notices?