More on the Matching Operator

We have already looked at the simplest uses of the matching operator (a regular expression enclosed in slashes). Now let’s look at a zillion ways to make this operator do something slightly different.

Selecting a Different Target (the =~ Operator)

Usually the string you’ll want to match your pattern against is not within the $_ variable, and it would be a nuisance to put it there (perhaps you already have a value in $_ you’re quite fond of). No problem. The =~ operator helps us here. This operator takes a regular expression operator on the right side, and changes the target of the operator to something besides the $_ variable—namely, some value named on the left side of the operator. For example:

$a = "hello world";
$a =~ /^he/;         # true
$a =~ /(.)\1/;       # also true (matches the double l)
if ($a =~ /(.)\1/) { # true, so yes...
                     # some stuff
}

The target of the =~ operator can be any expression that yields some scalar string value. For example, <STDIN> yields a scalar string value when used in a scalar context, so we can combine this with the =~ operator and a regular expression match operator to get a compact check for particular input, as in:

print "any last request? ";
if (<STDIN> =~ /^[yY]/) { # does the input begin with a y?
  print "And just what might that request be? ";
  <STDIN>; # discard a line of standard input
  print "Sorry, I'm unable to do that.\n";
}

In this case, <STDIN> yields the next line from standard input, which is then immediately used as ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.