-> 和有什么区别?和 :: 在 Perl 中 [英] What is the difference between -> and :: in Perl
问题描述
Perl 中 ::
和 ->
之间的确切区别是什么?
What is the exact difference between ::
and ->
in Perl?
->
有时会在 ::
不起作用的地方工作.
->
sometimes works where ::
does not.
推荐答案
::
有两个用途.
它是包名中的命名空间分隔符
It's the namespace separator in package names
use Foo::Bar; # Load Foo/Bar.pm
$Foo::Bar::var # $var in namespace Foo::Bar
附加到一个裸字后,它会创建一个字符串文字[1].
以下与 'hello'
相同,只是它在包 hello
不存在时发出警告:
The following is the same as 'hello'
except it warns if the package hello
doesn't exist:
hello::
->
有两个用途.
它用于取消引用.
It's used to dereference.
$array_ref->[$i]
$hash_ref->{$k}
$code_ref->(@args)
在方法调用中使用它来表示调用者.
It's used in method calls to denote the invocant.
CGI->new() # Static method call
$cgi->param() # Object method call
<小时>
您可能会问有什么区别
You're probably asking what's the difference between
Foo::Bar::mysub()
和
Foo::Bar->mysub()
前者是函数调用.后者是方法调用.方法调用类似于函数调用,但有两点不同:
The former is a function call. The latter is a method call. A method call is like a function call with two differences:
方法调用使用继承.
Method calls use inheritance.
方法调用将调用者(->
的剩余部分)作为第一个参数传递给 sub.
Method calls pass the invocant (what's left of the ->
) to the sub as its first argument.
{
package Foo::Baz;
sub new {
my ($class, $arg) = @_;
my $self = bless({}, $class);
$self->{arg} = $arg;
return $self;
}
sub mysub1 {
my ($self) = @_;
print($self->{arg}, "\n");
}
}
{
package Foo::Bar;
our @ISA = 'Foo::Baz';
sub mysub2 {
my ($self) = @_;
print(uc($self->{arg}), "\n");
}
}
my $o = Foo::Bar->new('hi'); # Same as: my $o = Foo::Baz::new('Foo::Bar', 'hi');
$o->mysub1(); # Same as: Foo::Baz::mysub1($o);
$o->mysub2(); # Same as: Foo::Bar::mysub2($o);
<小时>
注意事项
Notes
Foo->method
欺骗性地调用名为Foo
的子(如果它存在)(使用它作为调用者返回的值).Foo::->method
,意思是'Foo'->method
,没有.
Foo->method
deceptively calls the sub namedFoo
if it exists (using its the value it returns as the invocant).Foo::->method
, meaning'Foo'->method
, doesn't.
这篇关于-> 和有什么区别?和 :: 在 Perl 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!