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

Hi, I'm trying to do something relatively simple, but I'm still new to OO Perl and not quite sure of the way to do it. I have an object containing an XML::Twig object:
package Foo; sub new { my $class = shift; my $self = {}; $self->{PARSED} = []; $self->{TWIG} = XML::Twig->new( twig_handlers => { mybutton => \&_twig_handle_button }, pretty_print => 'indented' ); bless( $self, $class ); } sub _twig_handle_button { my ( $t, $section ) = @_; my $parsed_href = { ... }; &_handle_parsed_href( $parsed_href ); }
Now, what I want is to call _handle_parsed_href as a class method of Foo, so that it gets passed a $self variable that allows me to access the Foo class members, i.e.:
sub _handle_parsed_href { my ( $self, $parsed_href ) = @_; push @{$self->{PARSED}}, $parsed_href; }
I can't call "$self->_handle_parsed_href" since the twig handler is passed a reference to XML::Twig ($t) rather than the class I'm defining. Any wisdom would be much appreciated. Thanks =)

Replies are listed 'Best First'.
Re: Calling a class method
by rhesa (Vicar) on Jul 04, 2007 at 18:12 UTC
    Instead of passing a direct reference to the handler sub, you can wrap it in a closure:
    twig_handlers => { mybutton => sub { $self->_twig_handle_button(@_) }, },
    Then your handler sub becomes a full-fledged object method:
    sub _twig_handle_button { my ( $self, $t, $section ) = @_; my $parsed_href = {}; $self->_handle_parsed_href( $parsed_href ); }