Perl – How to use a code ref as a callback in Perl

callbackperlreferencescripting

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.

Best Solution

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?