gpt4 book ai didi

Perl OO 方法调用第一个参数值 (->)

转载 作者:行者123 更新时间:2023-12-01 00:15:18 25 4
gpt4 key购买 nike

就 Perl OO 而言,-> 到底做了什么?

例如我打了一个主电话:

$result = a::b->mymethod( );

在我定义 mymethod() 的包中,我使用了以下内容:

    my( $class ) = @_;

在 main 中,我显然没有向 mymethod() 传递任何参数,那么 $class 参数从何而来?有没有人对此有很好的解释或对此进行解释的文档?

最佳答案

“Method Invocation” section of the perlobj documentation解释。额外的强调是我的。

Method Invocation

For various historical and other reasons, Perl offers two equivalent ways to write a method call. The simpler and more common way is to use the arrow notation:

my $fred = Critter->find("Fred");
$fred->display("Height", "Weight");

You should already be familiar with the use of the -> operator with references. In fact, since $fred above is a reference to an object, you could think of the method call as just another form of dereferencing.

Whatever is on the left side of the arrow, whether a reference or a class name, is passed to the method subroutine as its first argument. So the above code is mostly equivalent to:

my $fred = Critter::find("Critter", "Fred");
Critter::display($fred, "Height", "Weight");

How does Perl know which package the subroutine is in? By looking at the left side of the arrow, which must be either a package name or a reference to an object, i.e., something that has been blessed to a package. Either way, that’s the package where Perl starts looking. If that package has no subroutine with that name, Perl starts looking for it in any base classes of that package, and so on.

关于Perl OO 方法调用第一个参数值 (->),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10784085/

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