Even if this doesn't solve your two stated problems, the very first thing you need to do is add this to the top (and then deal with any errors/warnings that may arise):
use strict;
use warnings;
use autodie; # or give a die option when opening each filehandle