gpt4 book ai didi

perl - 当方法是 CODEREF 时,继承如何工作?

转载 作者:行者123 更新时间:2023-12-02 09:23:37 25 4
gpt4 key购买 nike

Mojo::EventEmitter我们有下一行代码:

for my $cb (@$s) { $self->$cb(@_) }

其中$cb是回调的CODEREF

如果我写:会有什么不同吗?

for my $cb (@$s) { $cb->($self, @_) }

我认为继承将不起作用,因为 $cbCODEREF,因为它在 $cb 包含带有方法的字符串的情况下起作用姓名。因此,在这种情况下,重写的代码将起到类似的作用。

我明白了吗?还是错过了什么?

最佳答案

$cb是代码引用时,不检查继承。事实上,$self 根本没有被检查。


$cb是代码引用时,

$self->$cb(@_)

功能上与

相同
$cb->($self, @_)

这就是为什么 $cb 应该使用 can 获取,它遵循继承。

package Parent {
sub new { bless({ @_ }, shift) }
sub method { CORE::say("!"); }
}

package Child {
our @ISA = 'Parent';
}

my $self = Child->new();
my $method_name = 'method';

my $cb = $self->can($method_name)
or die("The object's class doesn't have method $method_name\n");

$self->$cb();

请注意,有些人使用

my $f = "function_name";
undef->$f();

作为替代

my $f = "sub_name";
no strict qw( refs );
$f->();

然而,使用方法调用来调用非方法是非常不合适的,并且这个技巧仅在子没有参数的情况下才有效。如果您确实对这种(适当的)使用no strict有疑问,您可以使用以下( documented )技巧:

my $f = "sub_name";
(\&$f)->(); # \&$f isn't subject to "use strict qw( refs );" checks

关于perl - 当方法是 CODEREF 时,继承如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39799314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com