Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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?
Simon

Comment on XML::Twig - Twig Handler question
Select or Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (13)
As of 2015-07-29 17:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (266 votes), past polls