Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing file handle as function arg in Perl

Tags:

perl

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

like image 873
amphibient Avatar asked Dec 19 '25 01:12

amphibient


1 Answers

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:

  • I reversed the argument to teeOutput to something saner.
  • I removed the directive (&) to override teeOutput's prototype. teeOutput doesn't even have one.

(But if you have to deal with globs, use teeOutput(\*STDERR, ...);.)

like image 102
ikegami Avatar answered Dec 21 '25 19:12

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!