LPM: Scope of $_

Frank Price fprice at mis.net
Tue Jan 11 21:22:38 CST 2000

On Tue, 11 Jan 2000, David Hempy wrote:

#  Okay, I'm either confused or disappointed about the scope of $_ ... tell me
#  which.


# rtf2html() uses $_ internally to do some stuff.  After it returns, $_ in
# scout.pl has the last value of rtf2html::$_ .  The message "$_ has changed
# at BBB!" gets printed out.
# I'm really confused by this.  I had assumed that $_ is scoped like my
# variables.  It certainly doesn't appear that way to me now.  In this
# example, the subroutine is in a different module with its own package,
# which is particularly disappointing.  Heck, I expected subroutines within
# the same .pl file to have their own $_ !  

Not sure about your own internal states, but I think you've
illustrated a good point: don't depend upon $_ !!.  On perl.com there
was an article called the Seven Sins of Perl Revisited which mentioned
this very thing.  Far from $_ being lexically scoped, it and the other
magical vars like $/, etc. are the only true globals in Perl since
they are the same across namespaces.

# All of a sudden I'm a bit nervous about using $_ through an entire
# subroutine, assuming that no deeper subroutines can/will affect it.  Of
# course I can copy $_ to my variables, but that takes some of the magic away
# from things like: 
# 	s/\n/<p>/g;

I usually explicitly name the loop var: foreach my $value (@values)

# 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.

Right, my $_ won't work.  I think that in your module you could do
local $_ to create your private copy though.


More information about the Lexington-pm mailing list