"调用方法与传递类/对象作为第一个参数之间到底有什么区别?-6ren"> "调用方法与传递类/对象作为第一个参数之间到底有什么区别?-来自perldoc perlobj (在这篇优秀的 answer 中引用): my $fred = Critter->find("Fred"); $fred->display("Height", "W-6ren">
gpt4 book ai didi

perl - 通过 "->"调用方法与传递类/对象作为第一个参数之间到底有什么区别?

转载 作者:行者123 更新时间:2023-12-03 02:00:35 25 4
gpt4 key购买 nike

来自perldoc perlobj (在这篇优秀的 answer 中引用):

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

... the above code is mostly equivalent to:

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

除了错误检查以确保第一个参数是受祝福的对象还是有效的类名之外,到底有什么区别?例如。为什么大部分相同但不完全相同?

最佳答案

假设 Critter 是一个没有定义 finddisplay 或两者的子类!正如 perlobj 文档所解释的那样,这种对应关系不是一一对应的,因为硬连线子调用不执行方法查找。

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.

对于子程序,您必须准确地知道它的静态位置,否则您的程序将死亡。要调用方法,您只需指定从哪里开始搜索它。

例如:

#! /usr/bin/env perl

package Critter;
sub new { bless {}, shift }
sub display { ref($_[0]) . " display" }

package SuperCritter;
@SuperCritter::ISA = qw/ Critter /;

package main;
my $super = SuperCritter->new;

# one of these things is not like the other
warn $super->display;
warn Critter::display($super);
warn SuperCritter::display($super);

输出:

SuperCritter display at ./call-demo line 14.SuperCritter display at ./call-demo line 15.Undefined subroutine &SuperCritter::display called at ./call-demo line 16.

关于perl - 通过 "->"调用方法与传递类/对象作为第一个参数之间到底有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10785082/

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