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)

In reply to Re: Arrays and Handles Problem (updated) by haukex
in thread Arrays and Handles Problem by Melly

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.