I am a bit new to Perl, but here is what I want to do:
my @array2d;
while(<FILE>){
push(@array2d[$i], $_);
}
It doesn't compile since @array2d[$i]
is not an array but a scalar value.
How should I declare @array2d as an array of array?
Of course, I have no idea of how many rows I have.
Creating Multidimensional Arrays You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
To make an array of arrays, or more accurately an array of arrayrefs, try something like this:
my @array = ();
foreach my $i ( 0 .. 10 ) {
foreach my $j ( 0 .. 10 ) {
push @{ $array[$i] }, $j;
}
}
It pushes the value onto a dereferenced arrayref for you. You should be able to access an entry like this:
print $array[3][2];
Change your "push" line to this:
push(@{$array2d[$i]}, $_);
You are basically making $array2d[$i] an array by surrounding it by the @{}... You are then able to push elements onto this array of array references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With