当我将数组推送到一个有一个数组作为唯一元素的数组数组时,为什么会得到这种数据结构呢?
use v6;
my @d = ( [ 1 .. 3 ] );
@d.push( [ 4 .. 6 ] );
@d.push( [ 7 .. 9 ] );
for @d -> $r {
say "$r[]";
}
# 1
# 2
# 3
# 4 5 6
# 7 8 9
say @d.perl;
# [1, 2, 3, [4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)
这是单个参数规则中描述的预期行为.
Perl 6在演变过程中已经经历了许多与扁平化有关的模型,然后才得出一个简单的称为"单一参数规则"的模型.
通过考虑for循环将执行的迭代次数,可以最好地理解单个参数规则.迭代的东西总是被视为for循环的单个参数,因此是规则的名称.
for 1, 2, 3 { } # List of 3 things; 3 iterations
for (1, 2, 3) { } # List of 3 things; 3 iterations
for [1, 2, 3] { } # Array of 3 things (put in Scalars); 3 iterations
for @a, @b { } # List of 2 things; 2 iterations
for (@a,) { } # List of 1 thing; 1 iteration
for (@a) { } # List of @a.elems things; @a.elems iterations
for @a { } # List of @a.elems things; @a.elems iterations
Run Code Online (Sandbox Code Playgroud)
...列表构造函数(中缀:<,>运算符)和数组作曲家([...]外围符号)遵循以下规则:
[1, 2, 3] # Array of 3 elements
[@a, @b] # Array of 2 elements
[@a, 1..10] # Array of 2 elements
[@a] # Array with the elements of @a copied into it
[1..10] # Array with 10 elements
[$@a] # Array with 1 element (@a)
[@a,] # Array with 1 element (@a)
[[1]] # Same as [1]
[[1],] # Array with a single element that is [1]
[$[1]] # Array with a single element that is [1]
Run Code Online (Sandbox Code Playgroud)
这些很可能提供惊喜的只有一个是[[1]],但它被认为是非常罕见,它不保证的例外情况很一般单个参数的规则.
所以为了完成这项工作我可以写:
my @d = ( [ 1 .. 3 ], );
@d.push( [ 4 .. 6 ] );
@d.push( [ 7 .. 9 ] );
Run Code Online (Sandbox Code Playgroud)
或者也
my @d = ( $[ 1 .. 3 ] );
@d.push( [ 4 .. 6 ] );
@d.push( [ 7 .. 9 ] );
Run Code Online (Sandbox Code Playgroud)