I would recommend the idiom:
while (local $_ = <$FH>)

This is certainly best practice -- it stops the while from mangling the caller's precious $_.

Unfortunately, being a good citizen doesn't prevent some mad person from running amuck with an Uzi and blowing away the firstborn.

Consider:

use strict ; use warnings ; my $mock = "I\nII\nIII\nIV" ; open my $FH, '<', \$mock ; $_ = 'firstborn' ; while (local $_ = <$FH>) { chomp ; print "$_=" ; tr/IV/iv/ ; amuck() ; print "$_ " ; } ; if (!defined($_)) { $_ = '*undef*' ; } ; print " -- $_\n" ; sub amuck { $_ = '!!!' } ;
which gives:
  I=!!! II=!!! III=!!! IV=!!!   -- firstborn
so we managed to keep the firstborn safe, but the loop is littered with bodies.

Of course, without the local $_, ie: the common or garden:

while (<$FH>)
everybody gets it:
   I=!!! II=!!! III=!!! IV=!!!   -- *undef*

Better is to lexically scope the $_, thus:

while (my $_ = <$FH>)
so that we can still implicitly use $_ in the loop, AND it now works (hurrah!):
   I=i II=ii III=iii IV=iv   -- !!!
OK. The firstborn has gone, but that serves you right for leaving it unattended outside in the push-chair.


In reply to Re^2: Just when you thought you'd got it: 'foreach $f (@foo)' vs 'foreach (@foo)' by gone2015
in thread Just when you thought you'd got it: 'foreach $f (@foo)' vs 'foreach (@foo)' by gone2015

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.