在Perl 6 签名文档中,有一个匿名slurpy参数的示例:
sub one-arg (@) { }
sub slurpy (*@) { }
one-arg (5, 6, 7); # ok, same as one-arg((5, 6, 7))
slurpy (5, 6, 7); # ok
slurpy 5, 6, 7 ; # ok子例程中没有语句,主要是因为它周围的文本是关于满足签名的参数列表,而不是子例程对它的处理方式。
我在玩这个游戏,并试图制作一个子例程,其中包含多个项目(所以,不是零项)。我不想说出他们的名字。我想,即使有签名,我仍然可以访问@_中的参数列表。但是,当您没有签名时,您将得到@_:
$ perl6
To exit type 'exit' or '^D'
> sub slurpy(*@) { say @_ }
===SORRY!=== Error while compiling:
Placeholder variable '@_' cannot override existing signature
------> sub⏏ slurpy(*@) { say @_ }是否有其他方法获取参数列表,或者匿名参数是否丢弃它们?我在关于类型约束的部分中看到了它们,但是没有使用任何参数值的示例。我还能拿到辩论名单吗?
发布于 2016-12-22 22:55:07
这些值不会被丢弃;例如,您可以通过下一次访问它
multi access-anon(*@) is default {
say "in first candidate";
nextsame;
}
multi access-anon(*@a) {
@a;
}
say access-anon('foo')输出:
in first candidate
[foo]但是要达到原来的目标(至少有一个元素的数组),您实际上不需要访问列表;您可以使用一个子签名:
sub at-least-one(@ [$, *@]) { }
at-least-one([1]); # no error
at-least-one([]); # Too few positionals passed; expected at least 1 argument but got only 0 in sub-signature发布于 2016-12-22 21:20:36
要填充@_,签名必须是隐式的或显式的,而不是两者兼而有之。
sub implicit { say @_ } # most like Perl 5's behaviour
sub explicit ( *@_ ) { say @_ }
sub placeholder { $^a; say @_ }这也适用于区块。
my &implicit = { say @_ }
my &explicit = -> *@_ { say @_ }
my &placeholder = { $^a, say @_ }块也可以有$_的隐式参数,但如果有@_,则优先。
{ say $_ }(5) # 5
$_ = 4;
{ @_; say $_ }(5) # 4这样做是有意义的,因为一个程序员可能会认为它的工作方式和你认为的一样,或者如果是隐式的话,它会变得很乏味,而另一个程序员可能会认为它得到了所有剩下的参数。
sub identical ( @_ ) { say @_ }
sub slurpy ( *@_ ( @, *@ ) ) { say @_ } # same as implicit
sub slurpy2 ( **@_ ( @, *@ ) ) { say @_ } # non-flattening
sub remaining ( @, *@_ ) { say @_ }
identical [1,2]; # [1 2]
slurpy $[1,2],3,4,5; # [[1 2] 3 4 5]
slurpy2 [1,2],3,4,5; # [[1 2] 3 4 5]
remaining [1,2],3,4,5; # [3 4 5]@_也可能被添加为一个错误,在这种情况下,它最好产生一个错误。
如果不声明捕获参数,就无法获得原始参数。
sub raw-one ( |capture ( @ ) ) { capture.perl }
sub raw-slurpy ( |capture, *@ ) { capture.perl }
raw-one [1,2]; # \([1, 2])
raw-slurpy 1,2 ; # \(1, 2)https://stackoverflow.com/questions/41290618
复制相似问题