2011-09-05 59 views
16
package a; 
sub func { 
print 1; 
} 
package main; 
a::->func; 

海事組織已經足夠擁有a::func,a->func爲什麼`a :: - > func;`有效?

a::->func;看起來很奇怪,爲什麼Perl支持這種奇怪的外觀語法?

+5

如果你認爲這* *語法是奇怪... – 2011-09-05 04:06:16

+9

的Perl既不需要也不是理由藉口。 Perl是Perl。 –

+0

@pst - 我敢給你一個陌生人:) – DVK

回答

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" 
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 
+1

+1。如果你告訴我如何不記得最後兩個,那麼另一個+1。 – DVK

+0

@DVK,'chr'是一個非常有用的功能。雖然這顯然不是使用它的地方。 'v97'是一個版本字符串,它作爲一個版本字符串甚至不是特別好。 – ikegami

相關問題