my $file="test.dat"; my $insert="foo"; { local $/ = undef; open(my $fh, '<', $file) or die "$!"; my $data = <$fh>; $data=~s/<\/body>/$insert\n<\/body>/; open(my $fh,'>',$file) or die "$!"; print $fh $data; close($fh); }