my $i = 1; my $string = 'print "hello";'; my $content = 'print "hello";$x + 2; print "hello";print "hello";print "hello";'; $content =~ s/($string)/$1.$i++."\n"/ge; print "$content\n"; eval $string;