Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

XML::Twig - provide additional parameters to twig_roots handlers

by kejv2 (Acolyte)
on Sep 30, 2012 at 19:59 UTC ( #996531=perlquestion: print w/replies, xml ) Need Help??
kejv2 has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,

I am parsing a xml file using XML::Twig like this:

XML::Twig->new( twig_roots => { 'div' => \&div } )->parsefile("my_file"); sub div { my ($t, $elt) = @_; # do something return 1; }

I have a run-time parameter which I want to get in div (or any other) element handler. How can I do this?

I would expect something like putting this parameter into XML::Twig constructor and then getting it from twig $t element. But there is nothing like this described in the documentation. The only way I can think about is to define own element handling package with method returning my parameter and putting this package as elt_class option into XML::Twig constructor. But that seems terribly artificial to me.

Any better ideas?

Replies are listed 'Best First'.
Re: XML::Twig - provide additional parameters to twig_roots handlers
by remiah (Hermit) on Sep 30, 2012 at 20:40 UTC

    I guess you are looking for 4.6 A simple HTML+ converter example.You can pass your $para to your function like this.

    XML::Twig->new( twig_roots => { 'div' => sub{ &div(@_,$para); }, } )->parsefile("my_file");
    and use it in your function
    sub div { my ($t, $elt,$para) = @_; ...
    I hope I understand your intention...

Re: XML::Twig - provide additional parameters to twig_roots handlers
by Jenda (Abbot) on Oct 01, 2012 at 07:11 UTC

    This has been discussed about two weeks ago in XML::Twig newbie question.

    Enoch was right!
    Enjoy the last years of Rome.

      Ah, so the solution is to use slight closure trick instead of being provided by the module itself, but that's ok. It's a pity that the topic you are referencing isn't properly named. Otherwise I could have maybe found the info myself...

        The thing is that you may very well want to have several different twig roots with different handlers and different piece of data to pass. XML::Twig could have given you a "pad" within the parser object that you could use to store something in between the handler calls, but (at least according to a quick scan ... I don't use XML::Twig myself) seems mirod did not think it's necessary.

        Yes, I agree that other thread is a bit hard to find.

        Enoch was right!
        Enjoy the last years of Rome.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://996531]
Approved by kcott
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2018-01-23 03:20 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (238 votes). Check out past polls.