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

Monks, I can't seem to find a way to do this. I would like to be able to specify the modifiers of a regular expression via a scalar. For example:
my $modifiers = 'i'; my $text = 'abc'; if ( $text =~ m/$pattern/$modifiers) { print "it matches\n"; }
The perl interpreter obviously doesn't like this because it is expecting an operator instead of the scalar $modifiers. Is there a way to do this other than a big if elsif statement that covers all of the various operators that may be in $modifiers? Using qr doesn't work any better to build the expression. Thanks in advance.

Replies are listed 'Best First'.
Re: Regular expression modifiers in a scalar
by Sidhekin (Priest) on Jul 24, 2006 at 03:20 UTC

    You want modifiers inside the regex:

    my $modifiers = 'i'; my $text = 'abc'; my $pattern = 'BC'; if ( $text =~ m/(?$modifiers:$pattern)/) { print "it matches\n"; }

    Only good for turning on (or off) options imsx. See perlre.

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

      Excellent. That is exactly what I was looking for! Thanks for the quick reply.
Re: Regular expression modifiers in a scalar
by Zaxo (Archbishop) on Jul 24, 2006 at 03:31 UTC

    The problem seems to be that $modifiers is not interpolated in time for the compiled regex to have seen it. This will work,

    if ( $text =~ m/(?$modifiers)$pattern/ ) { print "it matches\n"; }
    That is a facet of "Cloistered Pattern Modifiers", as covered on p186 of the Camel Book(3ed.).

    After Compline,
    Zaxo

      I don't know how I missed that section. I swear I paged through that chapter several times looking for the answer. I it is a small section I guess... Thanks again.