Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create multidimensional arrays in Perl?

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.

like image 691
Ben Avatar asked Nov 25 '08 13:11

Ben


People also ask

How do you create a multidimensional array?

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.


2 Answers

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];
like image 166
gpojd Avatar answered Oct 11 '22 16:10

gpojd


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.

like image 41
BrianH Avatar answered Oct 11 '22 17:10

BrianH