如何在Perl中从二维数组中提取数组?

ezykj2lf  于 2022-12-13  发布在  Perl
关注(0)|答案(1)|浏览(164)

我有一个二维数组,我想把第一个元素放入一个简单的数组:

use strict; use warnings;
use Data::Dump;

my @matrix = ([1,2,3], [4], [5,6]);
my @array  = (7,8,9);

my @list = $matrix[0];

print "matrix: " ; dd \@matrix;
print "array:  " ; dd \@array;
print "list:   " ; dd \@list;

print "size of matrix is ", scalar(@matrix), "\n";
print "size of array is  ", scalar(@array),  "\n";
print "size of list is   ", scalar(@list),   "\n";

如果我运行它,我会得到输出:

matrix: [[1, 2, 3], [4], [5, 6]]
array:  [7, 8, 9]
list:   [[1, 2, 3]]
size of matrix is 3
size of array is  3
size of list is   1

所以list看起来还是一个二维数组,如何从矩阵的第一个元素得到一个类似array的一维数组呢?

nxowjjhe

nxowjjhe1#

您引用了一个数组。您需要取消引用它。更改:

my @list = $matrix[0];

至:

my @list = @{ $matrix[0] };

更改后,输出如下:

matrix: [[1, 2, 3], [4], [5, 6]]
array:  [7, 8, 9]
list:   [1, 2, 3]
size of matrix is 3
size of array is  3
size of list is   3

请参阅perldsc

相关问题