jettero has asked for the wisdom of the Perl Monks concerning the following question:

This seems like an easy one ... so it's been buggin' me. How do ya pass $object->function to a callback function? If it were in the same package, I would say:
$something->set_call_back( \&localfunction );
How do ya do it if it's ... from $object? I tried this:
$something->set_call_back( \$this->func ); # or $something->set_call_back( \&{ $this->func }); # and $something->set_call_back( \( $this->func ) );
I'll keep pluggin, but I bet it's really obvious...

Replies are listed 'Best First'.
Re: function ref
by btrott (Parson) on Nov 13, 2000 at 11:13 UTC
    How about using can?
    $something->set_call_back( $this->can('func') );
    can returns a subref.

    You should use this method if inheritance matters to you, because can respects inheritance; if you directly take a reference to a sub in a package, and that sub is actually an inherited method, you'll have a problem. :) You won't have that problem with can.

Re: function ref
by chromatic (Archbishop) on Nov 13, 2000 at 10:49 UTC
    It's easy to do if you know the classname at compile time. It's possible, but slightly more difficult if you don't know until runtime.
    #!/usr/bin/perl -w use strict; package Foo; sub new { bless({}, $_[0]); } sub do_it { print "Doing something for $_[0]!\n"; } package main; my $foo = new Foo;
    The direct approach just needs a good reference.
    my $do_it = \&Foo::do_it; $do_it->('direct call');
    The other way requires a bit of magic to get the proper class name and build something roughly equivalent to the last approach.

    I like using eval for this sort of thing. Your mileage may vary, and you can go far with a typeglob.

    my $ref = ref($foo); my $do_it2; eval "\$do_it2 = \\&${ref}::do_it"; $do_it2->('indirect call');
    The eval uses backslashes to make sure $do_it2 isn't interpolated and the ampersand isn't escaped. The braces around foo let the interpreter know that we only want $ref not $ref::do_it ($do_it in the package named 'ref').

    Update: If I took the time to stop and to think about it, I would use can as the brilliant and thoughtful btrott so sagely postulates.