Re: accessing object variables from callback function




anno4000@xxxxxxxxxxxxxxxx wrote:
kaisung@xxxxxxxxx <kaisung@xxxxxxxxx> wrote in comp.lang.perl.misc:

I'm trying to write a Class which uses XML::Parser. XML::Parser uses
callback functions. If I use an object method as the callback
function, how can I access object variables from within that callback
function if it doesn't get passed a reference to $self?

Then don't use the object method, but use a closure that calls the
object method. You're not saying of what class the object method
is supposed to belong and what $self is going to be. I'll assume
XML::Parser and $parser respectively. See below (code untested).

Actually it's more likely that the OP intended Test::load to be a
method.

-----BEGIN PERL-----
package Test;

sub load {
my $parser = new XML::Parser(ErrorContext => 2);
$parser->setHandlers(Start => \&_start_handler);

Use a closure that encloses the object you want to call _start_handler()
with:

$parser->setHandlers(Start => sub { $parser->_start_handler });

sub load {
my $self = shift;
my $parser = new XML::Parser(ErrorContext => 2);
$parser->setHandlers(Start => sub { $self->start_handler } );
}

.