I have a 2D array, and I want to put the first element into a simple array:
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";
If I run that, I get output:
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
So it seems that list
is still a 2-dimensional array. How to I get a one-dimensional array similar to array
from the first element of matrix?
CodePudding user response:
You have a reference to an array. You need to dereference it. Change:
my @list = $matrix[0];
to:
my @list = @{ $matrix[0] };
After that change, this is the output:
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
Refer to perldsc