in reply to Pattern not manipulating file output

Open a tempory file, say "$file.tmp", write to that and then rename it to $file

Put

use strict; use warnings;
at the start of the script

Check you open the file handle

open IN, $file or die "Can't open $file: $!\n";