use Fcntl qw( &SEEK_SET ); open(FH, "+) { my $line = $_; chomp $line; $line =~ s/foo/f/g; push @output, $line; } my $output = join("\n", @output); seek(FH, 0 , SEEK_SET ); print FH $output, "\n"; truncate(FH, length($output) ); close(FH); exit 0;