I would like to be able to have a function that prints to a file but that does not open the file -- instead an already open file handle should be passed to it. That way the file opening and closing only happen once in the calling block of code.
I tried:
sub teeOutput
{
my $str = $_[0];
my $hndl = $_[1];
#print to file
print $hndl $str;
#print to STDOUT
print $str;
}
and then when calling that
open(RPTHANDLE, ">", $rptFilePath) || die("Could not open file ".$rptFilePath);
&teeOutput('blahblah', RPTHANDLE);
&teeOutput('xyz', RPTHANDLE);
close(RPTHANDLE);
but that didn't work.
Any idea how to accomplish this?
Thanks
First, stop using global variables for file handles.
open(my $RPTHANDLE, ">", $rptFilePath)
or die("Could not open file $rptFilePath: $!\n");
Then... Well, there is no "then".
teeOutput($RPTHANDLE, 'blahblah');
teeOutput($RPTHANDLE, 'xyz');
close($RPTHANDLE);
Notes:
teeOutput to something saner.&) to override teeOutput's prototype. teeOutput doesn't even have one.(But if you have to deal with globs, use teeOutput(\*STDERR, ...);.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With