http://qs321.pair.com?node_id=11145353


in reply to Filehandle in subroutine in use VRML.pm

I understand that you want to pass filehandles to functions with the added feature that if user specified an undefined handle, said function and the rest of the program should use default STDOUT.

Firstly, try and migrate from bareword filehandles to lexical ones, except when you use the standard ones: STDERR, STDIN, STDOUT. So avoid using open FH, '>', 'xyz'; in favour of my $fh; open $fh, '>', 'xyz';

printout() below accepts a reference to a variable containing the filehandle. If contents of ref are not defined then it sets them to STDOUT and then proceeds in printing to the filehandle by dereferencing the ref (using {$$fhref} the curlies are used for disambiguating the syntax). Setting the fhref to STDOUT affects the caller since it is a reference to a variable of the caller.

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; }

There is some serious potential bug with above code. In open $fh, '>', 'xxx';, if $fh is set to STDOUT (and not undef as is the usual use-case) then it redirects STDOUT to 'xxx'! This and because I prefer that the one who opens the filehandle to close it as well, I would not use this idea of printout() setting the filehanlde to STDOUT which can then be inherited to all subsequent calls by the caller. I find it an unecessary complication. But printout() printing to STDOUT if no filehandle was given, is fine logic to me. So:

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; }

bw, bliako