ike*_*ami 54
:: 有两个用途.
它是包名称中的命名空间分隔符
use Foo::Bar; # Load Foo/Bar.pm
$Foo::Bar::var # $var in namespace Foo::Bar
Run Code Online (Sandbox Code Playgroud)附加到一个裸字,它创建一个字符串文字[1].
以下内容相同,'hello'但如果包hello不存在则会发出警告:
hello::
Run Code Online (Sandbox Code Playgroud)-> 有两个用途.
它用于解除引用.
$array_ref->[$i]
$hash_ref->{$k}
$code_ref->(@args)
Run Code Online (Sandbox Code Playgroud)它在方法调用中用于表示调用者.
CGI->new() # Static method call
$cgi->param() # Object method call
Run Code Online (Sandbox Code Playgroud)你可能会问它们之间有什么区别
Foo::Bar::mysub()
Run Code Online (Sandbox Code Playgroud)
和
Foo::Bar->mysub()
Run Code Online (Sandbox Code Playgroud)
前者是函数调用.后者是方法调用.方法调用就像一个函数调用,有两个不同之处:
方法调用使用继承.
方法调用将调用者(左边的内容->)作为第一个参数传递给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);
Run Code Online (Sandbox Code Playgroud)
笔记
Foo->method欺骗性地调用名为sub的子命令Foo(使用它作为调用者返回的值).Foo::->method,意思是'Foo'->method,没有.当右侧是函数时->,它将左侧作为函数的第一个参数.所以下面的例子是等价的,如果$foo有一个对象包装Foo和Bar在包Foo中.->将解析继承的方法,使其更清洁,对对象更有用.
$foo->Bar();
Foo::Bar($foo);
Run Code Online (Sandbox Code Playgroud)
-> 也可以采取包名
Foo->Bar();
Foo::Bar('Foo');
Run Code Online (Sandbox Code Playgroud)
这意味着->通常在实例方法中使用,以便对象传递其自身和构造函数,以便构造函数知道要使用哪个包.这通常是一个参数,因此可以继承.