Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a code ref as a callback in Perl?

I have the following code in my class :


sub new {
    my $class = shift;
    my %args  = @_;
    my $self  = {};
    bless( $self, $class );
    if ( exists $args{callback} ) {
        $self->{callback} = $args{callback};
    }
    if ( exists $args{dir} ) {
        $self->{dir} = $args{dir};
    }
    return $self;
}

sub test {
  my $self = shift;
  my $arg  = shift;
  &$self->{callback}($arg);
}

and a script containing the following code :


use strict;
use warnings;
use MyPackage;

my $callback = sub {
   my $arg = shift;
   print $arg;
};

my $obj = MyPackage->new(callback => $callback);

but I receive the following error:

Not a CODE reference ...

What am I missing? Printing ref($self->{callback}) shows CODE. It works if I use $self->{callback}->($arg), but I would like to use another way of invoking the code ref.

like image 971
Geo Avatar asked Feb 12 '09 23:02

Geo


1 Answers

The ampersand is binding just to $self and not the whole thing. You can do curlies around the part that returns the reference:

&{$self->{callback}}($arg);

But the

$self->{callback}->($arg);

is generally considered cleaner, why don't you want to use it?

like image 185
Adam Bellaire Avatar answered Oct 02 '22 14:10

Adam Bellaire