- Getting Started
- Perl Variables
- Control Flow Constructs
- Altering Loop Control Flow
- A Few Special Perl Variables
- Regular Expressions
- Writing Your Own Functions
1.5 A Few Special Perl Variables
As you become more familiar with Perl, you will see many predefined names. Some of these names are filehandles, others are functions, while still others are arrays and variables. A few of these are used so often that we wanted to introduce them early in the book.
1.5.1 $_
The predefined variable $_ has many different uses in Perl. Often it is a default string for various operations. For example, the following code reads lines from a file until the end of the file is reached:
while($line = <STDIN>) { print $line; }
You may write this code more succinctly by relying on the default variable, $_. That is, if you do not specify the variable that receives the line being read, then it is as though you have coded as follows:
while($_ = <STDIN>) { print $_; }
Of course, there's no need to code as above, since the following is equivalent:
while(<STDIN>) { print $_; }
$_ can also be the default variable to be printed. Thus, the above may be written as:
while(<STDIN>) { print; }
Finally, we could use the modifier form:
print $_ while(<STDIN>);
There are also a host of functions that operate on $_ by default. Thus:
chop is the same as chop($_) chomp; is the same as chomp($_) split("") is the same as split("" , $_)
1.5.2 $.
Another special variable is $., the input line number. Here's a simple example that uses $. to print the line and line number of all lines read from <STDIN>:
print "$.\t$_" while(<STDIN>);
The \t is the tab character. Along with the \n (newline) and other escape sequences, it must be enclosed within double quotes to yield its intended meaning. Here is another simple example that prints the number of lines in a file:
while(<STDIN>) { } print "$.\n";