0

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); 
 }
xcvbnm
  • 69
  • 9

1 Answers1

7

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

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Wauw is it only because i didn't use "my". Very interesting to be honest. I should learn to use it. And thanks – xcvbnm May 19 '15 at 21:50
  • 4
    Because you didn't use `my`, your use of `@a` referred to the global `@a`, which is not recreated each time through the loop like you expected. `my @a` creates a new `@a` each time. – Andy Lester May 19 '15 at 21:51
  • @xcvbnm: You should `use strict` as ikegami says, and declare *all* your variables with `my` – Borodin May 20 '15 at 04:06
  • But in this scenario - also ensure you do that inside the loop - `my @a` outside the loop will have the same result - you push a reference to the same array each time. – Sobrique May 20 '15 at 09:17