Perl Operators   «Prev  Next»
Lesson 11Perl special $_ variable
Objective Write a program that uses the pattern-matching operators with a yes/no question.

Perl Pattern Matching Variable

There is one item we need to cover about the pattern-matching operators before you actually start to use them.
The three operators discussed in the last several lessons use the special $_ variable by default. The $_ variable is the default input and pattern-matching workspace. It is implicitly set in a while loop when the only parameter is a file input. In other words, these two loops are equivalent:

while(<>) { ... }
while($_ = <>) { ... }

Many functions and operators work with $_ by default to make certain common tasks easier to write. In fact, all of our examples in this lesson so far have used $_ as the pattern-matching space.
In order to use a different variable with these pattern-matching operators, you need use the =~ operator to specify the variable to use. For example, you could use the match operator like this:
while($line = <>) {
 print $line if $line =~ /hello/i;
}
Or, you could use the substitute operator like this:
while($line = <>) {
 $line =~ s/hello/Goodbye/ig;
 print $line;
}

Or, the translation operator could be done like this:
$line =~ tr/A-Z/a-z/;
When used in a logical sense (as in the match operator above), you can use !~ to negate the logical value. This example will print all the lines that do not have "hello" in them:
while($line = <>) {
 print $line if $line !~ /hello/i;
}

Pattern Matching Operator - Exercise

Click the Exercise link below to write a program that requires you to use the pattern-matching operators.
Pattern Matching Operator - Exercise