use strict; use warnings; use 5.010; my $str = 'abcd'; my $pattern = '(ab)'; if ($str =~ $pattern) { my $repl = "--$1"; say '$repl: ', $repl; say 'old $str: ', $str; $str =~ s/$pattern/$repl/; say 'new $str: ', $str; } --output:-- $repl: --ab old $str: abcd new $str: --abcd