in reply to Redirect Subroutine Output
I recommend one of the following. (All the code below are UNTESTED and may contain errors.)
sub foo { my $o = ""; $o .= "blah\n"; $o; } if ($to_file == 0) { print foo(); } else { print MYFILE foo(); }
sub foo { print "blah\n"; } my $OLDH; if ($to_file) { $OLDH = select MYFILE; } foo(); $OLDH and select $OLDH;
sub foo { my($O) = @_; print $O "blah\n"; } foo($to_file ? *MYFILE : *STDOUT);
sub foo { my($P) = @_; &$P("blah\n"); } foo($to_file ? sub { print MYFILE @_ } : sub { print @_ }); # or foo(sub { if ($to_file) { print MYFILE @_ } else { print @_ } });
our $O; sub foo { print $O "blah\n"; } $O = $to_file ? *MYFILE : *STDOUT; foo(); # OR sub foo { print O "blah\n"; } *O = $to_file ? *MYFILE{IO} : *STDOUT{IO}; # (the {IO} is not strictly needed but this way we avoid overwriting $ +O etc) foo(); # or same as above but like open O, ">&=", ($to_file ? *MYFILE : *STDOUT); # or you could even use *MYFILE instead of *O # OR sub foo { my($P) = @_; pri("blah\n"); } sub pri { if ($to_file) { print MYFILE @_ } else { print @_ } }
|
|---|