CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



Jasmine
Administrator

Mar 15, 2001, 6:06 AM

Post #1 of 1 (12774 views)
How do I efficiently match many regular expression Can't Post

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;
}


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives