my $fh = undef; print "1.fh is now $fh\n"; printout("some lines", \$fh); print "2.fh is now $fh\n"; printout("some lines", \$fh); print "3.fh is now $fh\n"; $fh = undef; # <<<< very important, else redirects STDOUT to xxx open $fh, '>', 'xxx'; printout("some lines", \$fh); print "4.fh is now $fh\n"; close $fh; sub printout { my ($lines, $fhref) = @_; $$fhref = *STDOUT unless $$fhref; print {$$fhref} $lines; } #### my $fh = undef; printout('some lines1', $fh); open $fh, '>', 'xxx'; printout('some lines2', $fh); close $fh; sub printout { my ($lines, $_fh) = @_; my $fh = $_fh ? $_fh : *STDOUT; print $fh $lines; }