LPM: Scope of $_

David Hempy hempy at ket.org
Tue Jan 11 19:20:44 CST 2000


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

In my program, scout.pl, I have @rtf_files which has a bunch of file names.
I use $_ to loop through them something like this:

>	foreach (@rtf_files) {
>
>		print "$_\n";
>
<...snip some stuff that works on the filename in $_...>
>
>
>		my $start_val = $_;
>		
>		print "\$\_ has changed at AAA! \n"  unless $_ eq $start_val;
>		$body = rtf2html::rtf2html ($rtf);
>		print "\$\_ has changed at BBB! \n"  unless $_ eq $start_val;
>		
>		$rtf_url = $_;


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 $_ !  

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;

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.


-dave


ps. FYI, here is the start of the module I'm calling, rtf2html.pm:
>
>package rtf2html;
>
>use strict;
>use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
>
>require Exporter;
>
>@ISA = qw(Exporter AutoLoader);
>@EXPORT = qw();
>
>$VERSION = '0.4';
>
>sub rtf2html {
>	$_ = shift;
>    my ($outfile) = @_;
>    my ($title, $hex, $tofile);
>	
>    s/\n//g;	# Word wraps lines mid-word...glue it all into one line.
>
<...snip: Lots of other things that modify $_ and eventually return it...>




--
David Hempy
Internet Database Administrator
Kentucky Educational Television




More information about the Lexington-pm mailing list