Hi there, a friend of mine has been struggling with an aspect of XML::Twig. He wants to be able to call private methods on his object from within the handlers. However the problem is that the handler params are the $twig and the element.

The solution i suggested is as follows, where the create_sub method is called which then creates a reference to $self before it is assigned to the handler.

Is this the correct way to do this? Or can someone suggest a better way.

#!/usr/bin/perl -w use warnings; use strict; package Stupid; { use XML::Twig; sub new { my ( $caller, $args ) = @_; my $class = ref($caller) || $caller; my $self = {}; $self->{a_note} = "This should print something\n"; bless $self, $class; my $code_ref = $self->create_sub; my $t = XML::Twig->new( twig_handlers => { 'a/b' => $code_ref +} ); my $xml = "<a><b>3</b><c>4</c></a>"; $t->parse($xml); $t->flush; } sub create_sub { my $hidden_self = shift; return sub { my ( $self, $t ) = @_; print ref($self) . "\n"; print ref($t) . "\n"; print $t->text; print "\n\n"; $hidden_self->gah(); }; } sub gah { my $self = shift; print ref($self) . "\n"; print "$self->{a_note}\n"; } }; my $s = Stupid->new();

In reply to XML::Twig and closures. by absolut.todd

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.