in reply to Arrays and Handles Problem
To give a little more information in addition to holli's answer: foreach (@testarray) loops over the array and assigns each element to $_, plus that iterator variable $_ is an alias to each original element of the array (see Foreach Loops), meaning that assigning to $_ changes the value in the original array. while (<DATA>) is actually while (defined($_ = readline DATA)) (I/O Operators), i.e. it is assigning to the same $_ variable.
If you use an explicit loop variable in the foreach, e.g. foreach my $elem (@testarray), the problem goes away, and you can also do the same in the while, e.g. while ( my $line = <DATA> ).
Update: Here you can see @testarray getting clobbered. The undef comes from the fact that <DATA> returns undef when it hits EOF (end of file).
use warnings; use strict; use Data::Dump; my @testarray = ([10,20],[30,40]); dd "A", @testarray; foreach (@testarray) { dd "B", @testarray; while ( <DATA> ) { dd "C", @testarray; } dd "D", @testarray; } dd "E", @testarray; __DATA__ hello world
Output:
("A", [10, 20], [30, 40]) ("B", [10, 20], [30, 40]) ("C", "hello\n", [30, 40]) ("C", "world\n", [30, 40]) ("D", undef, [30, 40]) ("B", undef, [30, 40]) ("D", undef, undef) ("E", undef, undef)
|
|---|