http://qs1969.pair.com?node_id=314801

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

I am using XML::Twig to convert XML from one form to another. I want to be able to use XML::Twig as part of a larger package where the subs reference one another via $self->subroutinename syntax as self contains allsorts of necessary config data. I have no issue using XML::Twig except for one thing.
The doc states setting up a callback to a twig handler is defined as :-
my $twig= new XML::Twig( TwigHandlers => # player will be call +ed { player => \&player } # when each player el +ement ); # has been parsed
I want to be able to set up a callback as :-
my $t= XML::Twig->new( twig_handlers => { 'JOB_SECTIONS/SWITCH' => $self->_upload_j +ob()}, pretty_print => 'indented' )->parsefile($InFileName);
However when I do this it breaks the twig handler as the twig and element are not passed into the sub. The sub is fired though. I could but would prefer not to have to code around this. Any ideas? How can I reference self if it isn't passed into the sub?
Simon

Replies are listed 'Best First'.
Re: XML::Twig - Twig Handler question
by mirod (Canon) on Dec 15, 2003 at 14:05 UTC

    The handler is always called with just 2 parameters, the twig and the element. So if you want to add new elements, you have to use a closure: make the handler an anonymous subroutine. It can then use lexicals in scope when it is defined. It might sound complicated, but practically it is very simpleand natural:

    my $t= XML::Twig->new( twig_handlers => { 'JOB_SECTIONS/SWITCH' => sub { $self->_up +load_job( @_) } },...

    You can get much better explanations about what's going on there in Simon Cozens Achieving Closure.

      That did the trick. Thanks.
      Really good module - made my life a lot easier - thanks