Interpolating into Patterns

The regular expression is double-quote interpolated as if it were a double-quoted string. This allows us to write a quick grep-like program like this:

    #!/usr/bin/perl -w
    my $what = "larry";

    while (<>) {
      if (/^($what)/) {  # pattern is anchored at beginning of string
        print "We saw $what in beginning of $_";
      }
    }

The pattern will be built up out of whatever’s in $what when we run the pattern match. In this case, it’s the same as if we had written /^(larry)/, looking for larry at the start of each line.

We didn’t have to get the value of $what from a literal string and could have gotten it from the command-line arguments in @ARGV:

    my $what = shift @ARGV;

If the first command-line argument is fred|barney, the pattern becomes /^(fred|barney)/, looking for fred or barney at the start of each line.[198] The parentheses (which weren’t necessary when searching for larry) have become important because without them we’d be matching fred at the start or barney anywhere in the string.

With that line changed to get the pattern from @ARGV, this program resembles the Unix grep command. But we have to watch out for metacharacters in the string. If $what contains 'fred(barney', the pattern will look like /^(fred(barney)/. You know that can’t work—it’ll crash your program with an invalid regular expression error. With some advanced techniques,[199] you can trap this kind of error (or prevent the magic of the metacharacters in the first place) so it won’t crash your program. But ...

Get Learning Perl, Fourth Edition 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.