Is it possible to make a "search and replace" work where the replacement is a variable containing $1, $2, ... special variables?

#!/usr/bin/env perl
use strict;
use warnings;
use 5.10.0;

my $row = 'ab';
my $pattern = '^(.)(.)';
my $replacement = '$2-$1';
$row =~ s/$pattern/$replacement/;
say $row; # $2-$1
2

There are 2 best solutions below

0
On BEST ANSWER

Use String::Substitution's sub_modify.

use String::Substitution qw( sub_modify );

sub_modify( $row, $pattern, $replacement );

Notes:

  • Use gsub instead of sub if you want the behaviour of the g modifier.
  • Use copy instead of modify if you want the behaviour of the r modifier.
1
On

"When all you have is a nail everything looks like a hammer."

If internal politics (corporate policy) inhibits the convenient installation of modules:

#!/usr/bin/env perl
use strict;
use warnings;
use 5.10.0;

my $row = 'ab';
my $pattern = '^(.)(.)';
#my $replacement= '$2-$1';
my $replacement;
#$row =~ s/$pattern/$replacement/;
$row =~ s/$pattern(?{$replacement="$2-$1"})/$replacement/e;
say $row; # b-a

Perhaps this do?