$a = "aaabbbaaa"; $b = "s/b/c/g"; eval '$a =~ ' . $b; #### local $_ = "aaabbbaaa"; $b = "s/b/c/g"; eval $b; #### # Inputs # ====== $string = "aaabbbaaa"; $regexp = "b"; $subst = "c"; $global = 1; # (?i...) can be used in $regexp for /.../i # (?m...) can be used in $regexp for /.../m # (?s...) can be used in $regexp for /.../s # (?x...) can be used in $regexp for /.../x # /g cannot be stored in $regexp, thus the need for $global. # /e cannot be stored in $regexp, but I'm not supporting it. # Guts # ==== # Check user input. eval { # Let's explicitely be on the safe side. no re 'eval'; $regexp = qr/$regexp/; }; # Handle bad user input. die("Bad regexp supplied: $@\n") if $@; # Do the work. if ($global) { $string =~ s/$regexp/$subst/g; } else { $string =~ s/$regexp/$subst/; }