in reply to How to apply modifiers to a substitution via variable?

I find the suggestions to use eval EXPR unwise and suggestions to use s///ee (eval EXPR's disguised form) deplorable. Don't generate code for eval that you can't easily validate. Fortunately, eval EXPR is not needed. Here's a copy of my earlier answer to the same question.

For imsx, you can use (?switches:pattern). For g, you'll have to use an if.

my $source = "abc"; my $find = "a"; my $replace = "x"; my %opts = ( i => 1, m => 0, s => 0, x => 0, g => 1, ); my $opts = join '', map { $opts{$_}?$_:'' } qw( i m s x ); my $re = "(?$opts:$find)"; if ($opts{g}) { $source =~ s/$re/$replace/g; } else { $source =~ s/$re/$replace/; } print $source;

Update: Fixed where %opts was referenced as %opt.

Replies are listed 'Best First'.
Re^2: How to apply modifiers to a substitution via variable?
by liverpole (Monsignor) on Feb 01, 2007 at 00:16 UTC
    Except that, since you didn't use strict or warnings, which IMO is just as "deplorable" as using eval, you've got a hidden error:
    use strict; use warnings; my $source = "abc"; my $find = "a"; my $replace = "x"; my %opts = ( i => 1, m => 0, s => 0, x => 0, g => 1, ); my $opts = join '', map { $opt{$_}?$_:'' } qw( i m s x ); my $re = "(?$opts:$find)"; if ($opt{g}) { $source =~ s/$re/$replace/g; } else { $source =~ s/$re/$replace/; } print $source;

    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re^2: How to apply modifiers to a substitution via variable?
by liverpole (Monsignor) on Feb 01, 2007 at 00:18 UTC

    Here's the output from ikegami's code above, (but with strict and warnings applied):

    Global symbol "%opt" requires explicit package name at test.pl line 16 +. Global symbol "%opt" requires explicit package name at test.pl line 19 +. Execution of test.pl aborted due to compilation errors

    Update:  To clarify a bit ... I don't really think that skipping use strict; and use warnings; is "deplorable".  But I also don't think that sometimes using eval or the /e modifier to a regular expression is, either. ;-)


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

      I didn't say it was tested code. And it's just a snippet to be inserted into a larger program with use strict and use warnings.

      And I didn't say /e (which is harmless), but /ee. If you're going to execute untrusted code, at least make it obvious. Don't hide it!