使用范围运算符分配给 3D 数组的一部分

Assigning to a slice of a 3D array using the range operator

我有一个 3 维数组。我想像这样设置它的三个元素:

$array[$x][$y][0 .. 2] = (0, 1, 2);

但是 perl 告诉我:

Useless use of a constant (1) in void context

在数组上下文中:

@array[$x][$y][0 .. 2] = (0, 1, 2);

但是 perl 告诉我:

syntax error near "]["

大概意思是它希望我给它两个索引,然后作为一个单独的数组分配给第三个维度?但是,在 this page 上,在 Example: Assignment Using Array Slices 下,它表明可以使用范围运算符分配给切片,其中显示:

@array1[1..3] = @array2[23..25];

我怎样才能像这样分配给数组的一部分,还是必须单独分配每个索引?

您需要取消引用内部数组:

@{ $arr[$x][$y] }[ 0 .. 2 ] = (0, 1, 2);

$array[$x][$y][0..2] 不是切片;这只是一个元素查找。

当您尝试将其更改为切片时,您切片了错误的数组。你切片 @arr 而不是 @{ $arr[$x][$y] }.

这里的关键是要认识到在 Perl 中没有 3d 数组这样的东西。您拥有的是对数组引用数组的引用数组,俗称数组数组数组,通常缩写为 AoAoA。

数组切片具有以下语法:

  • @NAME[LIST]
  • @BLOCK[LIST]
  • @$REF[LIST]
  • EXPR->@[LIST][1]

您可以使用以下任何一种:

  • 无法使用第一种语法,因为要切片的数组没有名称。
  • @{ $array[$x][$y] }[0..2] = 0..2;
  • my $ref = $array[$x][$y]; @$ref[0..2] = 0..2;
  • $array[$x][$y]->@[0..2] = 0..2;[1]

参见 Dereferencing Syntax


  1. 需要 Perl 5.24+。通过添加 use feature qw( postderef );no warnings qw( experimental::postderef );.
  2. 在 Perl 5.20+ 中可用