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

hello,

I have next code:
foreach (@node) { &traverse($_); } sub traverse { my($node)= @_; if ($node->getType == XML_ELEMENT_NODE) { print "<", $node->getName, ">"; foreach my $child ($node->childNodes()) { &traverse($child); } print "</", $node->getName, ">"; } elsif ($node->getType() == XML_TEXT_NODE) { print $node->getData; } }
What do I want to do? First I want to say I tried several things some so silly I don't dare to post :)

But I want to remove the print statments and catch the prints in a var, so I have the complete output of traverse in 1 var.Maybe I'll find the solution may self 'cos I will keep trying to find a solution myself. But maybe someone here can give some easy solution that I've missed to see :P

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

Edit Masem 2001-07-31 - Title change from "Code Logic"

  • Comment on Grouping output statements into one location during recursive operation
  • Download Code

Replies are listed 'Best First'.
Re: Code Logic
by Tyke (Pilgrim) on Jul 26, 2001 at 18:02 UTC
    Is there any reason that traverse can't take a reference to your variable, for instance...
    #!perl -w use strict; my $var; traverse($_, \$var) for @ARGV; print $var; sub traverse { my($node, $var)= @_; $$var .= $node . "\n"; traverse($node, $var) unless length $$var > 10; # to show it work recursively } __END__ varref a b c d a a a a a a b c d
    (Sorry about the simplified traverse)
Re: Code Logic
by Hofmator (Curate) on Jul 26, 2001 at 18:10 UTC

    Use a global variable our @results; and replace every print with push @results, "<".$node->somefun.">"; I hope this does what you meant.

    -- Hofmator

Re: Code Logic
by abstracts (Hermit) on Jul 26, 2001 at 18:23 UTC
    Hello,

    Why don't you do something like this:

    foreach (@node) { my $xml = traverse($_); print $xml; } sub traverse { my($node)= @_; if ($node->getType == XML_ELEMENT_NODE) { my $txt = "<" . $node->getName . ">"; foreach my $child ($node->childNodes()) { $txt .= traverse($child); } return $txt . "</" . $node->getName . ">"; } elsif ($node->getType() == XML_TEXT_NODE) { return $node->getData; } }
    Hope this helps,,,

    Aziz,,,

Re: Code Logic
by traveler (Parson) on Jul 26, 2001 at 21:21 UTC
      But their solutions don't work in my recursion situation :)

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

        Hello

        Can you please explain why the solutions we mentioned won't work in your recursive example?

        Aziz,,,