Perl Programming Page 2 - Understanding Perl's Special Variables |
One of the more important special variables you'll encounter in your Perl forays is $_, which is used by many Perl functions and constructs as the so-called "default variable" when none other exists. In order to demonstrate, consider the following example:
Here's the output:
In this case, the foreach() loop iterates over the hash, assigning the key The following example, which is equivalent to the one above, demonstrates:
Here, every time the loop iterates over the hash, since no instance variable is specified, Perl will assign the key to the default variable $_. This variable can then be printed via a call to print(). The $_ variable also serves as the default for both chop() and print() functions. Going back to the example above, you could also write it this way,
which would return
The $_ variable is also the default variable used by file and input handles. For example, consider the following simple Perl script, which prints back whatever input you give it: In this case, every line read by the standard input is assigned to the $_ variable, which is then printed back out with print(). Knowing what you now know about print() and $_, it's clear that you could also write the above as
The $_ default variable is used in a number of different places: it is the default variable used for pattern-matching and substitution operations; the default variable used by functions like print(), chop(), grep(), ord(), etc; the default instance variable in foreach() loops; and the default used for various file tests.
blog comments powered by Disqus |