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

Hi Perl Experts,  Question is similar to  http://www.perlmonks.org/?node_id=633541
my $results = call_api(a,b); #call_api returns following xml which gets stored in $results. <?xml version='1.0' standalone='yes'?> <response> </one/two/value> ……… ……… <//one/two/value> <rc>0</rc> <region>AUS</region> <user>User1</user> </response> $num='/one/two'; $val='value'; if(exists $results{"$num"/"$value"}) { do something }
Getting error at 'if(exists..' condition that << Can't use string ("<?xml version='1.0' standalone='") as a HASH ref while "strict refs" in use >> . But same code works in most cases. Can anyone kindly suggest the reason for the issue?

Replies are listed 'Best First'.
Re: XML header parsing error
by ~~David~~ (Hermit) on Jan 04, 2012 at 21:19 UTC
    You are trying to print a hash value with this line, but your variable is a scaler:

    $results{"$num"/"$value"};

    Maybe you want something like this:

    if( $results =~ /$num."\/".$value/m ) {

    Also use strict and warnings. You have some typos.

Re: XML header parsing error
by tobyink (Canon) on Jan 05, 2012 at 11:11 UTC

    Your error occurs because $results is a string, and you're trying to use it as a hashref. For example:

    use strict; my $foo = "Hello World"; exists $foo->{greeting}; # dies

    If you're trying to access your XML data as a hashref, then you probably want something like XML::Simple. However, there are a number of other errors and oddities with your code.

    • </one/two/value> is not even close to well-formed XML. No XML parser will be able to parse the XML sample you provided above.
    • $results{"$num"/"$value"} does not do what you think it does. The / is a numeric divide operator, so it treats "$num" and "$value" as numbers (both evaluate to 0). Dividing by zero will cause your code to die.