Variable Interpolation
Using Perl’s control-flow mechanisms to control pattern matching has its limits. The main difficulty is that it’s an “all or nothing” approach—either you run the pattern, or you don’t. Sometimes you know the general outlines of the pattern you want, but you’d like to have the capability of parameterizing it. Variable interpolation provides that capability, much like parameterizing a subroutine lets you have more influence over its behavior than just deciding whether to call it or not. (More about subroutines in the next chapter.)
One nice use of interpolation is to provide a little abstraction, along with a little readability. With regular expressions you may certainly write things concisely:
if ($num =~ /^[–+]?\d+\.?\d*$/) { ... }But what you mean is more apparent when you write:
$sign = '[–+]?';
$digits = '\d+';
$decimal = '\.?';
$more_digits = '\d*';
$number = "$sign$digits$decimal$more_digits";
...
if ($num =~ /^$number$/o) { ... }We’ll cover this use of interpolation more under Generated patterns later in this chapter. We’ll just point out
that we used the /o modifier to
suppress recompilation because we don’t expect $number to change its value over the course of
the program. This is no longer necessary because Perl has gotten smarter
about such things, but you may see it in older code.
Another cute trick is to turn your tests inside out and use the variable string to pattern match against a set of known strings:
chomp($answer = <STDIN>); if ("SEND" =~ /^\Q$answer/i) ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access