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


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:

@array = <FILE>;
close (FILE);

Need Your Help

How do I import ShowcaseView in Eclipse?

java android eclipse import showcaseview

ShowcaseView is contained in a Zip file here. But what exactly am I downloading and how do I import it in Eclipse?

When, if ever, should you use a "back to top" link?


I've seen many website designs with frequent inclusions of 'back to top' links and am just wondering when, if ever, they can really be justified? What use cases demand a 'back top top' link, and wh...