I am performing a string substitution in Perl, but I have both the pattern and the replacement strings stored as scalar variables outside the regular expression operators. The problem is that I want the replacement string to be able to use backreferences.
I hope the code below will illustrate the matter more clearly.
my $pattern = 'I have a pet (\w+).';
my $replacement = 'My pet $1 is a good boy.';
my $original_string = 'I have a pet dog.';
# Not Working
my $new_string = $original_string =~ s/$pattern/$replacement/r;
# Working
#my $new_string = $original_string =~ s/$pattern/My pet $1 is a good boy./r;
# Expected: "My pet dog is a good boy."
# Actual: "My pet $1 is a good boy."
print "$new_string\n";