I am trying to use variable interpolation in a replacement string including $1
, $2
,...
However, I can't get it to expand $1
into the replacement. I eventually will have the
$pattern
and $replacement
variables be read from a configuration file, but even
setting them manually doesn't work.
In the example script, you can see that the $1
(which should be 'DEF') is not
expanded in $new_name
, but it is in $new_name2
(without variables).
Adding an 'e' flag to the substitution doesn't help.
How do I fix this?
Matt
EXAMPLE CODE:
#!/usr/local/bin/perl
use strict;
my $old_name = 'ABC_DEF_GHI';
my $pattern = 'ABC_(...)_GHI';
my $replacement = 'CBA_${1}_IHG';
# using variables - doesn't work
my $new_name = $old_name;
$new_name =~ s|$pattern|$replacement|;
printf("%s --> %s\n", $old_name, $new_name);
# not using variables - does work
my $new_name2 = $old_name;
$new_name2 =~ s|ABC_(...)_GHI|CBA_${1}_IHG|;
printf("%s --> %s\n", $old_name, $new_name2);
OUTPUT:
ABC_DEF_GHI --> CBA_${1}_IHG
ABC_DEF_GHI --> CBA_DEF_IHG