Perl array reference always rewrites over itself in a loop

122 views Asked by At

I am trying to read some numbers from a text file and store it as a 2 dimensional array. I read a line and push into another array as an array reference. But I noticed that main array only has last line in all rows. How can i correct this? Thanks in advance. This is part i do it.

open IN, "a.txt";
@b=();

while (<IN>)

 { 
  $t =$_; 
  @a = split /\s+/,$t; 
  push(@b, \@a); 
 }
1

There are 1 answers

4
ikegami On BEST ANSWER

You only have only two arrays in total. You want one per line, plus @b. my creates a new variable each time it is executed, so you can use the following:

my @b;
while (<IN>) { 
    my @a = split;
    push @b, \@a; 
 }

By the way, you should always use use strict; use warnings;.