简体   繁体   English

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

[英]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 . 打印ref($self->{callback})显示CODE It works if I use $self->{callback}->($arg) , but I would like to use another way of invoking the code ref. 它可以工作,如果我使用$self->{callback}->($arg) ,但我想使用另一种方式来调用代码ref。

The ampersand is binding just to $self and not the whole thing. &符号仅限于$self而不是整个事物。 You can do curlies around the part that returns the reference: 你可以在返回引用的部分周围做curlies:

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

But the 但是

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

is generally considered cleaner, why don't you want to use it? 通常被认为是清洁的,为什么你不想使用它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM