Hi,

Chris Brown wrote:
 > i have read about it in 3 books and even used it in scripts i have
 > made but i still dont truly know how to be sure what $_ contains...
 > can anyone clear this up for me? Thanks


Interesting question, which can be answered in a multitude of ways.  The 
long and the short of it is that the perl variable "$_" is THE implicit 
variable.  It's the root of all evil, and the saviour of the language 
depending on how you look at it.

The documentation says, and I quote (perldoc perlvar):
---Documentation--
$_
$ARG

The default input and pattern-searching space. The following pairs are 
equivalent:
     while (<>) {...}    # equivalent only in while!
     while (defined($_ = <>)) {...}

     /^Subject:/
     $_ =~ /^Subject:/

     tr/a-z/A-Z/
     $_ =~ tr/a-z/A-Z/

     chomp
     chomp($_)

[snip]
--Documentation--

What the documentation tries to explain is that $_ is the default 
variable in much of perl.  The implicit use of $_ allows a person to 
write very very compact code which seems to "magically" do alot of 
things.  The use of $_ is rather often leads to code which doesn't (or 
does) reveal it's true purpose upon first read.  The use of avoidance of 
$_ is fairly core to perl's TAMWTDI.


Take the following example:

my @array = (0,1,2,3,4,5,6,7,8,9,10);
foreach(@array) {   # iterates through the array, placing the next value 
             # into $_
    print;           #  prints the implicit variable
                     #  equivaltent to print $_;
                
}

In essense, $_ is the hidden variable in the above loop.  It can be used to 

"un-hide" the default.

Here's another example:
# this example avoids using the "implicit" $_ variable.
open(FILE,"afile");
while(chomp(my $line = <FILE>)){
   $line =~ s/replacethis/withthis/g;
   if ($line =~ m/matchthis/) {
      do 'this';
   }
   print $line;
}
close(FILE);

# this example uses the "implicit" $_ variable, accomplishing the same
# thing as above
open(FILE,"afile");
while(<FILE>){
   chomp;
   s/replacethis/withthis/g;
   do 'this' if m/matchthis/;
   print;
}
close(<FILE>);

In the second example, $_ stands in for "the default input",  and what 
the loop is iterating over.

Hope that helps,

--Andy

Reply via email to