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

Dear monks,

am writing an simple program, its throwing error

#!/usr/local/bin/perl

$regex = '\d+';
$mod = 'i'
$string = 'my age is 30';

#if($string =~ m/$regex/i)    # -- works
if($string =~ m/$regex/$mod) # this line gives error
{
    print "Matched";
}
else
{
    print "not matched";
}


when i run it
BL05ACLS: ~ 51 > regex.cgi
Scalar found where operator expected at ./regex.cgi line 8, near "m/$regex/$mod"
syntax error at ./regex.cgi line 8, near "m/$regex/$mod"
Execution of ./regex.cgi aborted due to compilation errors.

Replies are listed 'Best First'.
Re: configurable regex match
by JavaFan (Canon) on Aug 13, 2009 at 16:42 UTC
    You can't do that. You cannot interpolate variables in random places in the program, and assume the parsing isn't going to happen until runtime. This is Perl, not a shell.

    But this should work:

    if ($string =~ /(?$mod)$regex/) { ... }
      Thanks it worked! You are a King!!
Re: configurable regex match
by biohisham (Priest) on Aug 13, 2009 at 17:46 UTC
    the context in which "i" is used in /$regex/i makes it a regular expression modifier. Perl supports quite a number of these modifiers for Regular Expressions...

    Anyhow, what you have been trying to achieve involves assigning to a scalar a character value, then using it as a modifier, whereas the compiler understands that in this place it wants to see a character corresponding to the action that the modifier implies instead.


    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.