Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

How do I efficiently match many regular expressions at once?

by faq_monk (Initiate)
on Oct 08, 1999 at 00:25 UTC ( #671=perlfaq nodetype: print w/ replies, xml ) Need Help??

Current Perl documentation can be found at

Here is our local, out-dated (pre-5.6) version:

The following is super-inefficient:

    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:

    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{

    $f2 = bm_or qw{

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

Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (11)
As of 2015-10-13 12:12 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (304 votes), past polls