[Mpls-pm] Interesting RegEx Problem

Nathan Graham ngraham at urth.org
Mon Sep 19 12:27:24 PDT 2005


> I need to rephrase the problem, though, because I realize I left a major
> aspect out of the phrasing:  Given a *collection of* strings and a
> collection of regular expression strings, where it is known that each
> string is matched by precisely one regular expression, how do you most
> efficiently develop the mapping?

If you have lots of patterns and only a few strings, then using the
study() function might speed things up.  If you just want a 1 to 1
mapping, then I would suggest using a two dimensional array like so:

use strict;

my @strings = qw(foo bar baz);
my @matches;

my %patterns = (
   foo => qr/foo/,
   bar => qr/bar/,
   baz => qr/baz/
);


for(@strings) {
    study;
    while ( my ( $name, $pattern ) = each %patterns )
        if (/$pattern/) {
            push(@matches, [ $_, $pattern ]);
            delete $patterns{$pattern};
        }
    }
}

for(@matches) { print "$_->[0] matches $_->[1]\n" }

Don't know if this helps. -Nathan



More information about the Mpls-pm mailing list