Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Perl中如何使用代码引用作为回调?_Perl_Reference_Scripting_Callback - Fatal编程技术网

在Perl中如何使用代码引用作为回调?

在Perl中如何使用代码引用作为回调?,perl,reference,scripting,callback,Perl,Reference,Scripting,Callback,我班上有以下代码: 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}

我班上有以下代码:


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)
,它是有效的,但是我想使用另一种调用代码引用的方法。

符号仅绑定到
$self
,而不是整个绑定。可以围绕返回引用的零件进行卷曲:

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

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

通常认为它更干净,为什么不使用它呢?

我的perl有点生锈了。我知道我遗漏了什么,我想知道那是什么:)。谢谢你,亚当!为什么需要另一种方法来取消对代码引用的引用?使用有效的方法并继续下一个问题。:)