Search code examples
perlreplacecapture-group

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


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

Solution

  • 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.