Home: Perl Programming Help: Frequently Asked Questions:
How do I efficiently match many regular expression



Jasmine
Administrator

Mar 15, 2001, 6:06 AM


Views: 32383
How do I efficiently match many regular expression

How do I efficiently match many regular expressions at once?

The following is super-inefficient:


Code
    while (<FH>) { 
foreach $pat (@patterns) {
if ( /$pat/ ) {
# do something
}
}
}

Instead, you either need to use one of the experimental Regexp extension modules from CPAN (which might well be overkill for your purposes), or else put together something like this, inspired from a routine in Jeffrey Friedl's book:


Code
    sub _bm_build { 
my $condition = shift;
my @regexp = @_; # this MUST not be local(); need my()
my $expr = join $condition => map { "m/\$regexp[$_]/o" } (0..$#regexp);
my $match_func = eval "sub { $expr }";
die if $@; # propagate $@; this shouldn't happen!
return $match_func;
}

sub bm_and { _bm_build('&&', @_) }
sub bm_or { _bm_build('||', @_) }

$f1 = bm_and qw{
xterm
(?i)window
};

$f2 = bm_or qw{
\b[Ff]ree\b
\bBSD\B
(?i)sys(tem)?\s*[V5]\b
};

# feed me /etc/termcap, prolly
while ( <> ) {
print "1: $_" if &$f1;
print "2: $_" if &$f2;
}