我想知道冒号与 Perl 6 中的方法和函数调用有什么关系。为了记录,我使用的是基于 MoarVM 版本 2015.05 构建的 perl6 版本 2015.05-55-gd84bbbc。
我刚刚在Perl6 规范测试(S32-io)中看到了以下内容(我添加了评论):
$fh.print: "0123456789A"; # prints '0123456789A' to the file
据我所知,这相当于:
$fh.print("0123456789A"); # prints '0123456789A' to the file
这两个似乎都需要多个参数并且可以很好地展平列表:
$fh.print: "012", "345", "6789A"; # prints '0123456789A' to the file
$fh.print("012", "345", "6789A"); # prints '0123456789A' to the file
my @a = <012 345 6789A>;
$fh.print(@a); # prints '0123456789A' to the file
$fh.print: @a; # prints '0123456789A' to the file
有这两种不同的语法一定是有原因的。有任何理由使用一种或另一种语法吗?
我还注意到,当用作方法时,我们必须使用:
或与 print 一起使用:()
$fh.print(@a); # Works
$fh.print: @a; # Works!
$fh.print @a; # ERROR!
在函数中使用冒号时还有一些有趣的行为print
。在这种情况下,:
和()
不等价:
print @a; # Prints '0123456789A' (no newline, just like Perl 5)
print(@a); # Ditto
print: @a; # Prints '012 345 6789A' followed by a newline (at least in REPL)
print @a, @a; # Error (Two terms in a row)
print: @a, @a; # Prints '012 345 6789A 012 345 6789A' followed by a newline (in REPL)
然后我尝试在脚本文件中使用 print 。这适用于打印到标准输出:
print @a;
但是,这不会打印到标准输出:
print: @a, @a;
但方法版本工作正常:
$fh.print: @a, @a; # Prints '0123456789A0123456789A' to the file
我觉得我几乎明白这一点,但我无法用语言表达。有人可以解释这些使用打印的品种吗?另外,这些行为是否会因为 Great List Refactor 而改变?