我的课堂上有以下代码:
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);
}
和一个包含以下代码的脚本:
use strict;
use warnings;
use MyPackage;
my $callback = sub {
my $arg = shift;
print $arg;
};
my $obj = MyPackage->new(callback => $callback);
但我收到以下错误:
Not a CODE reference ...
我错过了什么?印刷ref($self->{callback})
展示CODE
。如果我使用它可以工作$self->{callback}->($arg)
,但我想使用另一种调用代码参考的方式。