Perl – Send file handle as argument in perl

filehandleperl

Is it possible to send a file handle as an argument to a subroutine in PERL?

If yes, can you help with a sample code snippet showing how to receive it and use it in the subroutine?

Best Answer

You're using lexical variables (open(my $fh, ...)) as you should, right? If so, you don't have to do anything special.

sub f { my ($fh) = @_; print $fh "Hello, World!\n"; }
f($fh);

If you're using a glob (open(FH, ...)), just pass a reference to the glob.

f(\*STDOUT);

Though many places will also accept the glob itself.

f(*STDOUT);
Related Topic