# reading file into array and then process it # and write out to the same file: my $file = "./test.txt"; open (LOG, "+<$file"); flock LOG, 2; my @logfile=; seek (LOG, 0, 0); truncate (LOG,0); foreach my $line(@logfile){ # do some manipulations with $line... print LOG $line; } close LOG; #### # trying to optimize performance and memory usage # by replacing foreach() with while() my $file = "./test.txt"; my $tempfile = "./tempfile".(rand()*9999); open (LOG, $file); flock LOG, 1; open (TMP, ">$tempfile"); flock TMP, 2; while (my $line = ){ # here we do some manipulations with $line print TMP $line; } close TMP; rename($tempfile,"$file"); close LOG;