LPM: Scope of $_

AARON B. DOSSETT aaron at iglou.com
Tue Jan 11 21:05:07 CST 2000

> So you tell me...am I confused or disappointed?  I looked in Learning Perl
> and Programming Perl, but didn't find the answer.  Is there something I can
> do to protect $_ ?  I tried my ($_) but perl didn't like that.

You're disappointed, and rightly so.  There's only one $_ and a change made
to it anywhere is reflected everywhere else.  The solution is to rely on
$_ only in limited circumstances, i.e.: 

while (<IN>)
  next unless /foo/;

or to protect $_ when calling unknown subroutines, i.e.:

{local $_ = undef;

This will restore the value of $_ once you exit the code-block.

See item 3 of :   http://www.perl.com/pub/1999/11/sins.html  for more details.

Hope that helps,


More information about the Lexington-pm mailing list