Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

XML::Twig and closures.

by absolut.todd (Monk)
on Dec 14, 2007 at 06:20 UTC ( #656995=perlquestion: print w/replies, xml ) Need Help??

absolut.todd has asked for the wisdom of the Perl Monks concerning the following question:

Hi there, a friend of mine has been struggling with an aspect of XML::Twig. He wants to be able to call private methods on his object from within the handlers. However the problem is that the handler params are the $twig and the element.

The solution i suggested is as follows, where the create_sub method is called which then creates a reference to $self before it is assigned to the handler.

Is this the correct way to do this? Or can someone suggest a better way.

#!/usr/bin/perl -w use warnings; use strict; package Stupid; { use XML::Twig; sub new { my ( $caller, $args ) = @_; my $class = ref($caller) || $caller; my $self = {}; $self->{a_note} = "This should print something\n"; bless $self, $class; my $code_ref = $self->create_sub; my $t = XML::Twig->new( twig_handlers => { 'a/b' => $code_ref +} ); my $xml = "<a><b>3</b><c>4</c></a>"; $t->parse($xml); $t->flush; } sub create_sub { my $hidden_self = shift; return sub { my ( $self, $t ) = @_; print ref($self) . "\n"; print ref($t) . "\n"; print $t->text; print "\n\n"; $hidden_self->gah(); }; } sub gah { my $self = shift; print ref($self) . "\n"; print "$self->{a_note}\n"; } }; my $s = Stupid->new();

Replies are listed 'Best First'.
Re: XML::Twig and closures.
by mirod (Canon) on Dec 14, 2007 at 08:33 UTC

    I am not quite sure what you want to do here, but did you know that you "friend" (joking ;--) can generate a closure "on the fly"?

    It goes simply like this:

    my $self={}; XML::Twig->new( twig_handlers => { 'a/b' => sub { $self->my_method( @_ +); } ); ... sub my_method { my( $self, $t, $elt)= @_; ... }

    Simon Cozens' Achieving Closure article has more details on closures, using XML::Twig as an example.

    Does that help?

      Ahhhhh, and the lightbulb turns on! Thank you, that is exactly what i was trying to achieve for my "friend".

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2022-05-23 18:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (82 votes). Check out past polls.

    Notices?