swares has asked for the wisdom of the Perl Monks concerning the following question:

I figured this out the other day but today when I want to use it cannot find the notes I though I had saved. I have a regex loaded into a string which I need to use to do some matching. I've tried the following -
$string = 'My Test Data'; $regex = 'm/\btest\b/i'; if ($string =~ $regex){print "It Works!\n"}else{print "No joy!\n"};
and
$string = 'My Test Data'; $regex = 'm/\bTest\b/i'; $stmt = 'if ($string =~ $regex){print "It Works!\n"}else{print "No joy +!\n"}'; eval $stmt;

Replies are listed 'Best First'.
Re: Regex in string to be used for matching.
by ikegami (Patriarch) on Nov 09, 2009 at 20:57 UTC
    $regex contains a match operator (Perl source code), not a regex pattern.
    $string = 'My Test Data'; $regex = '(?i)\btest\b'; print $string =~ m/$regex/ ? "Match\n" : "No match\n";
    or just
    $string = 'My Test Data'; $regex = '(?i)\btest\b'; print $string =~ $regex ? "Match\n" : "No match\n";

    m// is implied if the RHS of =~ is not one of the ops that are affected by =~.

      $regex contains a match operator (Perl source code), not a regex pattern.

      Its just a string

      my $regex = qr!(?i)\btest\b!;

        The match operator will happily interpolate a pattern stored as a string. Compiled patterns have only existed since 5.6. qr// is not necessary.

        In fact, using qr// makes no sense here.

        If there's no reason for the pattern to be a string, you might as well just do

        $string = 'My Test Data'; print $string =~ m/\btest\b/i ? "Match\n" : "No match\n";

        But I bet there's a reason it's a string here. If so, you'd do

        $string = 'My Test Data'; $regex = '(?i)\btest\b'; print $string =~ $regex ? "Match\n" : "No match\n";

        If you were planning on using $regex repeatedly, then qr// could become useful.