in reply to Switching between output to file and STDOUT

Since what you're doing looks like logging, why not go full throttle and use Log::Log4perl:
my $outfile; use Log::Log4perl qw(:easy); Log::Log4perl->easy_init( {level => $DEBUG, file => (defined $outfile ? $outfile : "STDOUT")}); DEBUG "hey!";