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

Hi users of XML::Twig! I tried something like this:
sub mysub { my($t, $tag)= @_; foreach my $child ($tag->children) { # foreach my $grandchild ($tag->children) { # correction thanks to pg foreach my $grandchild ($child->children) { $grandchild->purge; } } }
and used this as a twig handler. I hope it's clear what I wanted to do. But I simply get the message that purge couldn't be located via XML::Twig::Elt. Can someone please tell me how to free the grand childs of my current element?

Replies are listed 'Best First'.
Re: purging of grandchildren in XML::Twig
by Zaxo (Archbishop) on Oct 19, 2003 at 04:33 UTC

    The purge method belongs to the XML::Twig object, not to the XML::Twig::Elt objects the tags produce. That is what the error message tells you.

    You probably want the delete() method of XML::Twig::Elt. Trusting you have the arguments as you want them,

    sub mysub { my ( $t, $tag) = @_; for ($tag->children) { $_->delete() for $_->children; } 1; }
    Note that the two $_ in the delete line are different. The one right of for belongs to the outer loop, the left to the inner. Somehow, it all works out ;-)

    After Compline,
    Zaxo

Re: purging of grandchildren in XML::Twig
by pg (Canon) on Oct 19, 2003 at 06:59 UTC

    PodMaster has already given solid answer base on his experience.

    Now you may wondering what purge actually does. Method purge is used to blow entire section away. There is also a method called flush does similar thing, but they handles output differently.

    XML::Twig uses memory very wisely, and purge and flush are part of the effort, so that you can quickly dispose a processed section if it is no longer needed.

    By the way, there might be a typo in your code, is it? Looks you are getting both child and granchild from $tag.

      That's what I wanted to do: Blow away an entire subtree. Example: If I have
      root +--X1 | +--Y1 | | +--Z1 | | \--Z2 | | | +--Y2
      and I'm currently in the root-node-handler, I may blow away all the Y's and everything below the Y's. So what I finally came up with is
      $t->purge_up_to($grandchild);
      And yes you're right: It was a typo.
Re: purging of grandchildren in XML::Twig
by PodMaster (Abbot) on Oct 19, 2003 at 04:44 UTC
    purge is a XML::Twig method, meaning you have to have a twig in order to call purge on it. It has been my experience that children does not return twigs.

    update: *sigh* I snooze, I snooze

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.