in reply to Dynamic regexp from array values

You could either build a regex
my $regex = join '|', map "\Q$_\E", @vals; doSomething() if $data =~ $regex;
Or better yet use Regex::PreSuf
use Regex::PreSuf; doSomething() if $data =~ presuf(@vals);
Or put grep() to use
doSomething() if grep $data =~ /\Q$_/, @vals;

HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: Dynamic regexp from array values
by bronto (Priest) on Feb 12, 2003 at 10:41 UTC
    You could either build a regex
    my $regex = join '|', map "\Q$_\E", @vals; doSomething() if $data =~ $regex;

    Actually my $regex = qr(join '|', map "\Q$_\E", @vals) will optimize the pattern matching. See perldoc -f qr

    Ciao!
    --bronto


    The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
    --John M. Dlugosz
      Actually my $regex = qr(join '|', map "\Q$_\E", @vals) will optimize the pattern matching
      Hrm, that's debatable, check out diotalevi's reply in meaning of /o in regexes.
      HTH

      _________
      broquaint

      Actually my $regex = qr(join '|', map "\Q$_\E", @vals) will optimize the pattern matching

      Unfortunately I'll be a totally different pattern though. Dispite the looks of it, qr() is not a function call. It's a quote operator with () as delimiters. You need to either interpolate the join() call (with e.g. @{[join ...]}), or just do $regex = qr/$regex/.

      Update: Had misplaced the parenthesis.

      ihb