perl6 – 在Perl 6中使用冒号进行方法和函数调用

前端之家收集整理的这篇文章主要介绍了perl6 – 在Perl 6中使用冒号进行方法和函数调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道冒号与Perl 6中的方法函数调用有什么关系.
为了记录,我使用的是基于MoarVM版本2015.05的perl6版本2015.05-55-gd84bbbc.

我刚刚在Perl6 spec test (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","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,这些行为会发生变化吗?

解决方法

使用冒号而不是parens的主要原因之一是它可以通过删除一组parens帮助整理代码.否则它们完全一样.

当你打印:@a时,你真正在做的是在线上放一个标签,然后让@a掉头. REPL中的哪一个会调用值来表示.

如果在方法调用中不使用parens或冒号,那么将调用方法而不使用参数.

您可以交换方法的顺序,如果使用冒号,则可以调用invocant.

say $*ERR: 'hello world'; # $*ERR.say('hello world')

猜你在找的Perl相关文章