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:

perl -e '$_ = 100; for(1..5){};print;'
Produces '100', not '5'. Obviously for localizes $_, but apparently while does not...

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:

#... open FLOORFILE, $floorfile or die $!; { local($_); while (<FLOORFILE>) { print "$_\n"; } } #...
Now the output is this:
... building2 floor1 aldfja;jd;af floor2 aldfja;jd;af floor3 aldfja;jd;af

Celebrate Intellectual Diversity


In reply to Re: Problem with while loop inside a foreach loop by InfiniteSilence
in thread Problem with while loop inside a foreach loop by andylevel2

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.