package a;
sub func {
print 1;
}
package main;
a::->func;
IMO足以拥有a::func
,a->func
。
a::->func;
对我来说很奇怪,为什么Perl支持这种奇怪的语法?
答案 0 :(得分:25)
引用chromatic在Modern Perl blog上关于该主题的优秀近期博客文章:“避免使用匿名解析歧义。”
为了说明为什么这样的语法有用,这里是一个从你的样本演变而来的例子:
package a;
our $fh;
use IO::File;
sub s {
return $fh = IO::File->new();
}
package a::s;
sub binmode {
print "BINMODE\n";
}
package main;
a::s->binmode; # does that mean a::s()->binmode ?
# calling sub "s()" from package a;
# and then executing sub "open" of the returned object?
# In other words, equivalent to $obj = a::s(); $obj->binmode();
# Meaning, set the binmode on a newly created IO::File object?
a::s->binmode; # OR, does that mean "a::s"->binmode() ?
# calling sub "binmode()" from package a::s;
# Meaning, print "BINMODE"
a::s::->binmode; # Not ambiguous - we KNOW it's the latter option - print "BINMODE"
答案 1 :(得分:9)
a::
是一个字符串文字,用于生成字符串a
。一切都是这样的:
a->func() # Only if a doesn't exist as a function.
"a"->func()
'a'->func()
a::->func()
v97->func()
chr(97)->func()
等
>perl -E"say('a', a, a::, v97, chr(97))"
aaaaa