in reply to Regex in string to be used for matching.

$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 =~.

Replies are listed 'Best First'.
Re^2: Regex in string to be used for matching.
by Anonymous Monk on Nov 09, 2009 at 22:02 UTC
    $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.