use File::Temp qw(tempfile); my $file = 'test.txt'; my($tmpfh, $tmpfile) = tempfile(); open my $fh, '<', $file; binmode $fh; while (<$fh>) { # Process $_ here print $tmpfh $_; } close $fh; close $tmpfh; rename $tmpfile, $file; #### use Fcntl qw(:seek); use File::Temp qw(tempfile); my $file = 'test.txt'; my $tmpfh = tempfile(); open my $fh, '<', $file; binmode $fh; while (<$fh>) { # Process $_ here print $tmpfh $_; } close $fh; seek $tmpfh, 0, SEEK_SET; open my $fh2, '>', $file; binmode $fh2; print $fh2 $_ while <$tmpfh>; close $fh2; close $tmpfh;