use strict; use warnings; my $debug_flag = 0; # not debugging by default $debug_flag = $ARGV[0] if @ARGV == 1; $debug_flag = ( $debug_flag eq lc ( '-debug' ) )? 1 : 0; if ( $debug_flag ) { open DEBUG_FILE, ">debug.out" or die "Cannot open debug file for writing: $!"; } my $output; # do stuff to get the output $output = 'This is a test' . "\n"; print $output; print DEBUG_FILE $output if $debug_flag; # etc... #### # warning, not tested my $out_fh; if ( $debug_flag ) { open FILE, ">debug.out" or die $!; $out_fh = *FILE; } else { $out_fh = *STDOUT; } # and then always do: print $out_fh $output; # it will go to the right place.