spelee has asked for the wisdom of the Perl Monks concerning the following question:

I'm reading a table of data from a file using the following:
while(<>) { chomp; my (@stuff) = split(","); push(@lines, \@stuff); } $size=@lines; # just printing the 4th element in each row. for($i=0; $i<$size; $i++) { print("item: $lines[$i]->[3]\n"); }
Now I noticed that when I use "my", it seems to read the table and print the 4th element for each row properly.
But when i don't use "my", it seems to read all the rows but only print the 4th element for the last row $size number of times.
Can anyone explain to me why this is happening?
Thanks!!!

Replies are listed 'Best First'.
Re: question about the function "my"
by kvale (Monsignor) on Apr 30, 2004 at 15:45 UTC
    The my causes a new lexical variable @stuff to be created each iteration of the while loop. Thus each element of @lines is a reference to a different array.

    By contrast, without the my, @stuff is an ordinary global variable. Each iteration assigns it different values, but it is the same array, with the same reference each time around. Thus all the elements of @lines would point to the same array and you would naturally get the last values assigned to that array.

    -Mark

•Re: question about the function "my"
by merlyn (Sage) on Apr 30, 2004 at 15:41 UTC