Perl 将ArrayRef解包为X个单独的参数

Perl 将ArrayRef解包为X个单独的参数,perl,Perl,给定一个包含其他arrayref的arrayref,是否可以使用中的zip函数将嵌套的arrayref压缩在一起 例如,给定此arrayref: my $matrix = [ [qw( 1 2 3 4)], [qw( 5 6 7 8)], [qw( 9 10 11 12)], [qw(13 14 15 16)], [qw(17 18 19 20)], ]; 我想把每一行压缩在一起,这样我就可以换位了。预期产出: [ [qw(1 5 9 13 1

给定一个包含其他arrayref的arrayref,是否可以使用中的zip函数将嵌套的arrayref压缩在一起

例如,给定此arrayref:

my $matrix = [
   [qw( 1  2  3  4)],
   [qw( 5  6  7  8)],
   [qw( 9 10 11 12)],
   [qw(13 14 15 16)],
   [qw(17 18 19 20)],
];
我想把每一行压缩在一起,这样我就可以换位了。预期产出:

[
   [qw(1 5  9 13 17)],
   [qw(2 6 10 14 18)],
   [qw(3 7 11 15 19)],
   [qw(4 8 12 16 20)],
];
我最初的尝试是:

# I had hoped the function would unpack the arguments
zip @$matrix; 
# ERROR: Not enough arguments for List::MoreUtils::mesh at spiral.pl line 17

# I thought this slice would suffice to unpack them
zip @$matrix[1..scalar @$matrix-1]; 
# ERROR: Type of arg 1 to List::MoreUtils::mesh must be array (not array slice)

我相信有一种方法可以做到优雅,我只是没有看到它。任何帮助都将不胜感激

zip函数非常烦人,因为它使用了或类似于疯狂的东西。您必须执行一个符号和调用来覆盖原型:
&zip(@$matrix)

但是,您正在尝试转换矩阵,而不是将其转换为
zip
it(这将生成一个连续的列表,如

[1, 5, 9, 13, 17, 2, 6, 10, 14, 18, 3, 7, 11, 15, 19, 4, 8, 12, 16, 20]
我们可以将
natatime
迭代器与
zip
结合使用:

my $iter = natatime @$matrix, &zip(@$matrix);
my @transposed;
while (my @column = $iter->()) {
    push @transposed, \@column;
}
这是可行的,但这严重过度考虑了问题。让我们交换指数:

my $transposed = [];
for my $i (0 .. $#$matrix) {
    for my $j (0 .. $#{ $matrix->[0] }) {
        $transposed->[$j][$i] = $matrix->[$i][$j];
    }
}

只需使用以下功能的
转置

产出:

[
  [1, 5, 9, 13, 17],
  [2, 6, 10, 14, 18],
  [3, 7, 11, 15, 19],
  [4, 8, 12, 16, 20],
]

我最初的想法是,如果我在所有行上使用zip运算符,它将生成转置;我忘了它不会生成嵌套数组。不过交换索引要干净得多。谢谢,这正是我想要的。
[
  [1, 5, 9, 13, 17],
  [2, 6, 10, 14, 18],
  [3, 7, 11, 15, 19],
  [4, 8, 12, 16, 20],
]