English 中文(简体)
通过“ - >” 称呼一种方法与通过类/对象作为第一参数之间究竟有什么区别?
原标题:What exactly is the difference between calling a method via "->" vs passing class/object as first parameter?

来自perldoc perlobj (引用于此极好的<回答):

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

.上述代码主要相当于:

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

究竟有什么区别, 留下错误检查以确认第一个参数是一个幸运对象或一个有效的类名吗? 例如, 为什么它“ 坚固” 基本上是 , 但并不完全相同?

最佳回答

Say Critter 是没有定义 find display 的子类 。 信件不是一对一, 因为硬联线子电话不会像 perlobj 文件所解释的那样进行方法搜索 。

Perl 怎么知道子例程在哪个包件中? 通过查看箭头左侧, 它必须是包件名称或对象的引用, i. e. , 是包件的特惠。 不论哪种方式, 包件是 Perl 开始寻找的。 如果包件没有该名称的子例程, Perl 开始在包件的任何基类中寻找它, 等等 。

对于子集,您必须确切知道它静态地在哪里, 或者您的程序会 die 。 要调用一种方法, 您只需要指定在哪里开始搜索它 。

例如:

#! /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.
问题回答

暂无回答




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...