gpt4 book ai didi

perl - sub foo : method { shift->bar(@_) }? 使用的语法是什么

转载 作者:行者123 更新时间:2023-12-04 10:56:31 25 4
gpt4 key购买 nike

sub foo : method { shift->bar(@_) }

什么 : method这里的意思?

我从来没有这样用过...

最佳答案

: methodfunction attribute描述。如此标记的子例程不会触发“歧义调用解析为 CORE::%s”警告。

来自 ysth的评论 :

The warning happens when the sub has the same name as a builtin and it is called without & and not as a method call; perl uses the builtin instead but gives a warning. The :method quiets the warning because it clearly indicates the sub was never intended to be called as a non-method anyway.



更新

此代码仅调用方法 barfoo叫做:
sub foo : method {  ## Mark function as method
shift->bar(@_) ## Pass all parameters to bar method of same object
}

更多细节:
  • : method - 表示被引用的子程序是一个方法。如此标记的子例程不会触发“歧义调用解析为 CORE::%s”警告。
  • shift - 从 @_ 获取第一个参数,这将是 $self
  • ->bar(@_) - 调用同一个类的方法 bar与所有其他参数

  • 你可以这样读:
    sub foo : method {
    my ($self) = shift @_;
    return $self->bar(@_);
    }

    关于perl - sub foo : method { shift->bar(@_) }? 使用的语法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7169633/

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