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

I'd like to be able use a method as a handler. The problem I run into is passing the "self" reference through and handler while maintaining the handler's parameters. How can I make this work?
my $twig = new XML::Twig( twig_handlers => { _all_ => $self->proc_list, }, ); sub proc_list { my $self = shift; my $ele = shift; return if($ele->name eq '#PCDATA'); my $xpath = $ele->xpath; print $xpath,"\n"; }
$ele is always empty inside proc_list.

Replies are listed 'Best First'.
Re: Mixing handlers with methods
by Joost (Canon) on Dec 11, 2006 at 16:15 UTC
    The easiest way is to use an anonymous subroutine to call your method:
    # i'm assuming $self is actually defined here somewhere... my $twig = new XML::Twig( twig_handlers => { _all_ => sub { $self->proc_list(@_) }, }, );

    addendum:

    $ele is always empty inside proc_list.
    That's because in your code you're not passing the proc_list method, you're passing the result of calling $self->proc_list; which 1) is called before the XML::Twig object is even constructed, and 2) does not pass any arguments beside $self to proc_list.

Re: Mixing handlers with methods
by shamu (Acolyte) on Dec 11, 2006 at 17:01 UTC
    Thanks! That seems to work. I was originally dubious about just passing @_ to the handler and expecting it to work.