$data =~ s{(foo)(bar)}{ my $one = $1; my $two = $2; $one .= <<'END_TEXT'; $one.$two; }e; Insert 1 Insert 2 END_TEXT