Having just read the section in Damian's Object Oriented Perl book about the regular use of
qr, this looked like a good chance to try it out. That is, with
qr, you are creating a reference to a regular expression which you can store in a scalar variable. When that scalar variable is used in a regex later on, the complilation work to prepare the referenced regex doesn't have to be repeated each time through your loop, avoiding a good amount of regex overhead.
Here's the snippet again with some tweaks to your example. Note, whenever I store a reference in a scalar, I like to suffix the identifier with _Xr, where X stands for the kind of thing that's supposed to be referenced (in this case r for "regex") and the closing r indicates that the scalar is supposed to hold a reference.
#!/usr/local/bin/perl -w
use strict;
my @names = ("John?", "Paul", "George", "Rin.go");
my $regexStr
= "^static\\s+\\w+\\s+("
# Thanks moritz!
. (join "|",map quotemeta,@names)
. ")\\W.*";
print "$regexStr\n\n";
my $regexStr_rr = qr{$regexStr}i; # or "cloister" the 'i' in $regexStr
while(<DATA>) {
chomp;
my ( $hit )
= $_ =~ /$regexStr_rr/;
if ($hit) {
print "Beatle method \"$hit\" found on this line: $_\n";
}
else {
print "No Beatle method found on this line: $_\n";
}
}
__DATA__
static int lars(...);
static bool george(...);
static int thom(...);
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.