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.

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

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.


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.


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.


Another simple way is to use a hash table and use the two array indices to make a hash key:

$two_dimensional_array{"$i $j"} = $val;

If you're just trying to store a file in an array you can also do this:

fopen(FILE,"<somefile.txt");
@array = <FILE>;
close (FILE);

Need Your Help

IE not caching static content

asp.net caching iis webforms web-config

We have a .NET 3.5 WebForms Application and have an issue with client caching. Internet explorer (Tried on IE11) refuses to cache any static content such as css, js or images. However, it works per...

Python / Django Rest Framework weird error happening only when using debugger

python django django-rest-framework

This question has been SOLVED by myself after better looking at it. Please read my answer below.