home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeLearning Perl, 3rd EditionSearch this book

9.4. Interpolating into Patterns

The regular expression is double-quote interpolated, just 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.

But we didn't have to get the value of $what from a literal string; we could have gotten it instead from the command-line arguments in @ARGV:

my $what = shift @ARGV;

Now, if the first command-line argument were fred|barney, the pattern becomes /^(fred|barney)/, looking for fred or barney at the start of each line.[197] The parentheses (which weren't really necessary when searching for larry) are important, now, because without them we'd be matching fred at the start or barney anywhere in the string.

[197]The astute reader will know that you can't generally type fred|barney as an argument at the command line because the vertical bar is a shell metacharacter. See the documentation to your shell to learn about how to quote command-line arguments.

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 would look like /^(fred(barney)/, and you know that can't work right -- it'll crash your program with an invalid regular expression error. With some advanced techniques,[198] you can trap this kind of error (or prevent the magic of the metacharacters in the first place) so that it won't crash your program. But for now, just know that if you give your users the power of regular expressions, they'll also need the responsibility to use them correctly.

[198]In this case, you would use an eval block to trap the error, or you would quote the interpolated text using quotemeta (or its \Q equivalent form) so that it's no longer treated as a regular expression.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.