my $pat = qr/foo(\d+)bar(\d+)/; my $rep = 'x$1y$2'; my $str = 'foo36bar47'; $str =~ s/$pat/dyn_replace($rep)/e; print "$str\n";