Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

XML::Twig - Twig Handler question

by set_uk (Pilgrim)
on Dec 15, 2003 at 12:13 UTC ( #314801=perlquestion: print w/replies, xml ) Need Help??

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?

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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2022-12-08 18:32 GMT
Find Nodes?
    Voting Booth?

    No recent polls found