两者之间的确切区别是什么::
and ->
在 Perl 中?
->
有时在哪里工作::
才不是。
::
有两个用途。
-
它是包名称中的命名空间分隔符
use Foo::Bar; # Load Foo/Bar.pm
$Foo::Bar::var # $var in namespace Foo::Bar
-
Appended to a bareword, it creates a string literal[1].
下面的内容是一样的'hello'
除非它警告包裹hello
不存在:
hello::
->
有两个用途。
-
它用于取消引用。
$array_ref->[$i]
$hash_ref->{$k}
$code_ref->(@args)
-
它在方法调用中用于表示调用者。
CGI->new() # Static method call
$cgi->param() # Object method call
您可能会问两者之间有什么区别
Foo::Bar::mysub()
and
Foo::Bar->mysub()
前者是函数调用。后者是方法调用。方法调用类似于函数调用,但有两点不同:
-
方法调用使用继承。
-
方法调用传递调用者(调用者剩下的部分)->
) 到 sub 作为它的第一个参数。
{
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
,没有。更多关于此here https://stackoverflow.com/q/77046381/589924.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)