Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top