in reply to Problem with while loop inside a foreach loop
There were answers provided but I was missing the all critical, 'why does it happen this way?' One quick test shows that it probably should not:
Produces '100', not '5'. Obviously for localizes $_, but apparently while does not...perl -e '$_ = 100; for(1..5){};print;'
From Programming Perl Section 4.4.1: Unlike the foreach loop we'll see in a moment, a while loop never implicitly localizes any variables in its test condition. This can have "interesting" consequences when while loops use globals for loop variables.
So you don't really need to add new variables at all. You need to force Perl to localize $_, like so:
Now the output is this:#... open FLOORFILE, $floorfile or die $!; { local($_); while (<FLOORFILE>) { print "$_\n"; } } #...
... building2 floor1 aldfja;jd;af floor2 aldfja;jd;af floor3 aldfja;jd;af
Celebrate Intellectual Diversity
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Problem with while loop inside a foreach loop
by Laurent_R (Canon) on May 03, 2013 at 22:06 UTC | |
by Anonymous Monk on May 03, 2013 at 22:25 UTC | |
by Laurent_R (Canon) on May 04, 2013 at 11:02 UTC | |
|
Re^2: Problem with while loop inside a foreach loop
by andylevel2 (Initiate) on May 07, 2013 at 10:42 UTC | |
|
Re^2: Problem with while loop inside a foreach loop
by andylevel2 (Initiate) on May 07, 2013 at 10:47 UTC |