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

Here's a problem that has dogged me for years. I want to be able to define a string that contains regex criteria, and then use that within an actual regex expression. For example:

$criteria = "(abc|123)\$"; $teststring = "Foo walks up and says: abc"; if ( $teststring =~ /$criteria/ ) { print "it worked!\n"; }

Problem is, it doesn't work. A workaround is to not use the parenthesis in the $criteria and instead do:
$teststring =~ /($criteria)/
....but that seems like a hack. Is there a better way to do this aside from eval (which has its own problems, particularly if $criteria is being defined through a user-specified value from a web page).

thanks
Nept

Replies are listed 'Best First'.
Re: $scaler inside a RegEx
by mikeraz (Friar) on Aug 05, 2005 at 00:15 UTC

    It doesn't?

    mikeraz@tire:~$ cat tpl #!/usr/bin/perl $criteria = "(abc|123)\$"; $teststring = "Foo walks up and says: abc"; if ( $teststring =~ /$criteria/ ) { print "it worked!\n"; } else { print "uh no, it did not\n"; } mikeraz@tire:~$ ./tpl it worked! mikeraz@tire:~$

    is there more code around or between the statements?

    Be Appropriate && Follow Your Curiosity
      Better yet:
      $criteria = "(abc|123)\$"; $teststring = "Foo walks up and says: abc"; if ( $teststring =~ /$criteria/ ) { print "Got $1\n"; } else { print "uh no, it did not\n"; } __END__ output ====== Got abc
      You might have an easier time at typing your regexp if you used qr// instead of double quotes:
      $criteria = qr/(abc|123)$/; ...
Re: $scaler inside a RegEx
by polypompholyx (Chaplain) on Aug 05, 2005 at 10:47 UTC