member callback function

S

Shea Martin

How to I pass a member function as a callback.

For a normal sub I would do this: \&myFunc,

but what do I do for a member func?
I tried this, but it doesn't work: \&$myClassInstance->myFunc()
I also tried a number of other things.

~S
 
X

xhoster

Shea Martin said:
How to I pass a member function as a callback.

For a normal sub I would do this: \&myFunc,

but what do I do for a member func?
I tried this, but it doesn't work: \&$myClassInstance->myFunc()
I also tried a number of other things.

~S

sub { $myClassInstance->myFunc(@_) }

Xho
 
A

A. Sinan Unur

How to I pass a member function as a callback.

Instance methods do not exist independently of a specific instance of
the class. Just as you cannot cut the arm of a master knitter and send
it to another location, and expect it to work, you cannot expect an
instance method to do anything useful without the rest of the object.
For a normal sub I would do this: \&myFunc,>
but what do I do for a member func?
I tried this, but it doesn't work: \&$myClassInstance->myFunc()
I also tried a number of other things.

You'll need to use a closure. The code below is untested (as you have
not provided any code -- see the recommendations in the posting
guidelines for this group on how you can maximize both the quantity and
quality of the help you receive by putting some effort into your post).

#!/usr/bin/perl

use strict;
use warnings;

package My::Handler;

sub new {
my $class = shift;
bless { }, $class;
}

sub handle {
my $self = shift;
print "Go away, I am handling this!\n";
}

package My::Dispatcher;

sub new {
my $class = shift;
bless { }, $class;
}

sub register_callback {
my $self = shift;
$self->{callback} = shift;
}

sub generate {
my $self = shift;
$self->{callback}->();
}

package main;

my $dispatcher = My::Dispatcher->new;
my $handler = My::Handler->new;
$dispatcher->register_callback( sub { $handler->handle } );

$dispatcher->generate;

__END__
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top