Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

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.[] 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.

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,[*] you can trap this kind of error (or prevent the magic of the metacharacters in the first place) ...

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.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page