my @numbers = <4 8 15 16 23 42>;
这个有效:
.say for @numbers[0..2]
# 4
# 8
# 15
但这不是:
my $range = 0..2;
.say for @numbers[$range];
# 16
下标似乎将 $range
解释为范围 (3) 中的元素数。什么给了?
最佳答案
按预期工作。使用 @numbers[|$range]
将范围对象展平为列表或者在 Range 对象上使用绑定(bind)来传递它们。 https://docs.perl6.org将很快更新。
On Fri Jul 22 15:34:02 2016, gfldex wrote:
> my @numbers = <4 8 15 16 23 42>; my $range = 0..2; .say for
> @numbers[$range];
> # OUTPUT«16»
> # expected:
> # OUTPUT«4815»
>
This is correct, and part of the "Scalar container implies item" rule.
Changing it would break things like the second evaluation here:
> my @x = 1..10; my @y := 1..3; @x[@y]
(2 3 4)
> @x[item @y]
4
Noting that since a range can bind to @y in a signature, then Range being a
special case would make an expression like @x[$(@arr-param)]
unpredictable in its semantics.
> # also binding to $range provides the expected result
> my @numbers = <4 8 15 16 23 42>; my $range := 0..2; .say for
> @numbers[$range];
> # OUTPUT«4815»
> y
This is also expected, since with binding there is no Scalar container to
enforce treatment as an item.
So, all here is working as designed.
关于raku - 使用 Range 变量作为下标获取位置切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38535690/