develooper Front page | perl.perl5.porters | Postings from November 1999

[ID 19991126.002] overwriting with scalar $_ using foreach overarray and inner wh ile loop

Thread Previous
From:
Martyn Pearce
Date:
November 26, 1999 06:48
Subject:
[ID 19991126.002] overwriting with scalar $_ using foreach overarray and inner wh ile loop
Message ID:
14398.39955.821058.607227@kingsbury.inpharmatica.co.uk


Koester, Bernd writes:
| Using default scalar $_ (implicit) in an foreach loop over an array
| and having an inner while loop reading a file we noticed that perl is 
| overwriting the scalar of the outer loop inserting read lines 
| from the file into the array.
| 
| my @array=(1,2,3);
| foreach (@array) {
|    open FILE, "<test";
|    while <FILE> {
|       ...
|       }
|    close FILE;
|    }
| 
|  
| FILE contains just one character (a).
| After this procedure @array contains (a,a,a)!

This is not a bug:

man perlsyn ------------------------------------------------------------

The foreach modifier is an iterator: For each value in EXPR, it aliases
$_ to the value and executes the statement.

------------------------------------------------------------------------

man perlop -------------------------------------------------------------

If and ONLY if the input symbol is the only thing inside the conditional
of a while or for(;;) loop, the value is automatically assigned to the
variable $_.

------------------------------------------------------------------------

Hence the while loop assigns to $_ which is an alias into @array.  No
surprise.

Mx.

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About