my $myVar='old yeller'; my $b = 'cat $1 dog $2 mouse $myVar'; $_ 'hello sir, I am wally, the greeter'; # Use a substitution to replace the matched parts with $b s/(hello).+(wally).+/$b/; #### s/(hello).+(wally).+/sub { $b =~ s/\$\d+/$$1/g; }/;