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

Hello,

Yesterday I posted a problem with recursion. I a good answer with a small test that worked.

But in my situation it didn't work why? I don't know, I'm even trying to figure out how the debugger works :)

Here's my code:
use strict; use XML::LibXML; my $dom = XML::LibXML->new->parse_file('XMLS/PXMLStatusMessage.xml'); my $root = $dom->getDocumentElement(); my @node = $root->findnodes("//partnerContact/companyName"); my $all; foreach (@node) { &traverse($_, \$all); } print "DEBUG:\n".$all; sub traverse { my ($node, $all) = @_; if ($node->getType == XML_ELEMENT_NODE) { $$all .= "<", $node->getName, ">\n"; print "<", $node->getName, ">\n"; foreach my $child ($node->childNodes()) { &traverse($child,$all); } $$all .= "</", $node->getName, ">\n"; print "</", $node->getName, ">\n"; } elsif ($node->getType() == XML_TEXT_NODE) { $$all .= $node->getData."\n"; print $node->getData."\n"; } }
My output and errors:
Useless use of a constant in void context at ./myparse.pl line 31. Useless use of a constant in void context at ./myparse.pl line 36. <companyName> Planet Internet </companyName> DEBUG: <Planet Internet
Well I'm just trying to figure out why the prints work and my catching of the output in a variable doesn't?? Am I missing something about references?

--
My opinions may have changed,
but not the fact that I am right

Replies are listed 'Best First'.
Re: Recursion problem
by ChemBoy (Priest) on Jul 27, 2001 at 17:41 UTC

    I think your problem is here:

    $$all .= "</", $node->getName, ">\n";
    which should be changed to
    $$all .= "</" . $node->getName . ">\n";
    for two reasons. First, .= has higher precedence than the comma (which is why you're getting those void context warnings, I think). Second, the reason it's higher precedence is that as far as I know, .= evaluates its RHS in scalar context: assigning a list to it doesn't get you anywhere.



    If God had meant us to fly, he would *never* have given us the railroads.
        --Michael Flanders

Re: Recursion problem
by clemburg (Curate) on Jul 27, 2001 at 16:56 UTC

    The declaration my ($node, $all) = @_; in traverse() does shadow your global variable $all defined in my $all; above. That could be part of the problem.

    Update: No, it's not the problem. You use the global $all for the value and the local $all for a reference to this. I think ChemBoy found your problem.

    Christian Lemburg
    Brainbench MVP for Perl
    http://www.brainbench.com