Perl OO 方法调用第一个参数值 (->) [英] Perl OO method call first argument value (->)

查看:46
本文介绍了Perl OO 方法调用第一个参数值 (->)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就 Perl OO 而言,-> 究竟是做什么的?

In terms of Perl OO, what exactly does -> do?

例如我拨打 main:

For example I make a call main:

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

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

In the package where I define mymethod(), I use the following:

    my( $class ) = @_;

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

In main, I clearly don’t pass any arguments to mymethod(), so where is the $class argument coming from? Has anyone got a good explanation for this or a document that explains this?

推荐答案

perlobj 的 方法调用"部分文档 解释.额外的重点是我的.

The "Method Invocation" section of the perlobj documentation explains. The added emphasis is mine.

出于各种历史和其他原因,Perl 提供了两种等效的方法来编写方法调用.更简单、更常用的方法是使用箭头符号:

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");

您应该已经熟悉 -> 运算符与引用的使用.事实上,由于上​​面的 $fred 是对对象的引用,您可以将方法调用视为另一种解引用形式.

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");

Perl 如何知道子程序在哪个包中?通过查看箭头的左侧,它必须是包名称或对某个对象的引用,,某个包已被祝福的东西.无论哪种方式,这都是 Perl 开始寻找的包.如果该包没有具有该名称的子例程,Perl 将开始在该包的任何基类中查找它,依此类推.

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 方法调用第一个参数值 (->)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆