How can I create multidimensional arrays in Perl?

49,681

Solution 1

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];

Solution 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.

Solution 3

Have a look at perlref and perldsc to see how to make nested data structures, like arrays of arrays and hashes of hashes. Very useful stuff when you're doing Perl.

Solution 4

There's really no difference between what you wrote and this:

@{$array2d[$i]} = <FILE>;

I can only assume you're iterating through files.

To avoid keeping track of a counter, you could do this:

...
push @array2d, [ <FILE> ];
...

That says 1) create a reference to an empty array, 2) storing all lines in FILE, 3) push it onto @array2d.

Share:
49,681
Ben
Author by

Ben

Updated on July 09, 2022

Comments

  • Ben
    Ben almost 2 years

    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.