use File::Replace 'replace2'; my ($infh,$outfh) = replace2($filename); while (<$infh>) { # write whatever you like to $outfh here print $outfh "X: $_"; } close $infh; # closing both handles will close $outfh; # trigger the replace #### #!/usr/bin/env perl use warnings; use strict; use File::Replace 'replace2'; my $filename = "/tmp/test.html"; my @to_insert = ( '

Hello,', 'World! It is '.gmtime(time).' UTC

' ); my ($ifh,$tfh) = replace2($filename); my $found; while (<$ifh>) { print $tfh $_; if (//i) { $found=1; print $tfh "$_\n" for @to_insert; } } close $ifh; close $tfh; die "Marker not found" unless $found;