Passing file descriptor as arg function in Perl

I would like to be able to have a function that prints to a file but does not open the file - an already open file descriptor must be passed instead. This way, opening and closing a file only happens 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

open(RPTHANDLE, ">", $rptFilePath) || die("Could not open file ".$rptFilePath);

&teeOutput('blahblah', RPTHANDLE);
&teeOutput('xyz', RPTHANDLE);

close(RPTHANDLE);

      

but it didn't work.

Any idea how to do this?

thank

+3


source to share


1 answer


First stop using globals for file descriptors.

open(my $RPTHANDLE, ">", $rptFilePath)
   or die("Could not open file $rptFilePath: $!\n");

      

Then ... Well, no "then."

teeOutput($RPTHANDLE, 'blahblah');
teeOutput($RPTHANDLE, 'xyz');
close($RPTHANDLE);

      



Notes:

  • I changed the argument teeOutput

    to something more robust.
  • I removed the ( &

    ) directive to override the prototype teeOutput

    . teeOutput

    doesn't even have one.

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

.)

+10


source







All Articles