in reply to Re: Regexp substitution using variables
in thread Regexp substitution using variables

It's working, and crucially supports back-references

That's interesting as I cannot get this to support back-references...this is very similar to my initial attempt. So I have attempted to replicate it:

use strict; my $pattern = '(testing)'; my $replacement = 'New \1'; my $flags = 'i'; my $value = 'My Testing Text'; $replacement =~ s/\\/\\\\/g; eval "\$value =~ s/$pattern/$replacement/$flags"; print "$value\n";
This prints
My New \1 Text
It doesn't substitute the capture.

Replies are listed 'Best First'.
Re^3: Regexp substitution using variables (updated)
by AnomalousMonk (Archbishop) on Nov 26, 2020 at 03:19 UTC

    The OPed sort of problem is tricky, but for this specific iteration:

    Win8 Strawberry 5.8.9.5 (32) Wed 11/25/2020 22:12:13 C:\@Work\Perl\monks >perl use strict; use warnings; my $pattern = '(testing)'; my $replacement = 'New \U$1'; my $flags = 'i'; my $value = 'My Testing Text'; ### $replacement =~ s/\\/\\\\/g; print "replacement '$replacement' \n"; eval "\$value =~ s/$pattern/$replacement/$flags"; print "$value\n"; ^Z replacement 'New \U$1' My New TESTING Text
    (An escaped backreference \1 is not kosher in a replacement string anyway; it should be in $1 form.)

    Update: Here's a version of the example code that better illustrates the process of building the evaluation string:

    Win8 Strawberry 5.8.9.5 (32) Wed 11/25/2020 22:45:44 C:\@Work\Perl\monks >perl use strict; use warnings; my $pattern = '(testing)'; my $replacement = 'New \U$1'; my $flags = 'i'; my $value = 'My Testing Text'; print "replacement '$replacement' \n"; my $eval_string = "\$value =~ s/$pattern/$replacement/$flags"; print "eval_string '$eval_string' \n"; eval $eval_string; print "$value\n"; ^Z replacement 'New \U$1' eval_string '$value =~ s/(testing)/New \U$1/i' My New TESTING Text


    Give a man a fish:  <%-{-{-{-<