(my $adj = $1) =~ s/\d/3/g; # No parentheses needed. ($res = $str) =~ s{ (\d+) }{ ($adj = $1) =~ s/\d/3/g; $adj }xe; # Parentheses only needed in the outer substitution.