Normal use of filehandles:
open FH, ">$file" or die "Cannot write file [$file]: $!\n"; while(<FH>) { ... } close FH;