Using the $_ (default) Variable

Congratulations! You now know (just about) everything you need to know about loops in Perl (and anything else you're curious about, you can find out in “Going Deeper.”) Let's finish up with two general topics that we'll use quite a lot throughout the rest of this book: the special $_ variable, and the syntax for reading input from files on the Perl command line.

First, the $_ variable. This is a special variable in Perl that you can think of as being a default placeholder for scalar values. Lots of different constructs in Perl will use the $_ if you don't give them a specific scalar variable to deal with; this has the advantage of making your scripts shorter and more efficient—but sometimes it can make them more confusing to read.

One use of the $_ variable is in foreach. Remember that the foreach loop takes a temporary variable in which each element of the list is stored. If you leave off that temporary variable, Perl will use $_ instead. Then, inside the body of the foreach, you can refer to $_ to get to that value:

foreach (sort keys %hash) {
   print "Key: $_ Value: $hash{$_} 
";
}

Many functions will also use the value of $_ if you don't give them any arguments—print and chomp being prime examples. So, for example if you see what appears to be a bare print in someone's script, like this:

print;

Then, mentally add the $_ on the end of it:

print $_;

The $_ variable is very common throughout Perl, so get used to seeing it and remembering the places where it can be used. We'll look more at the $_ variable in the next section and quite a lot more on Day 9, “Pattern Matching with Regular Expressions.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset