Send file handle as argument in perl

Daanish picture Daanish · Dec 4, 2012 · Viewed 11.9k times · Source

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?

Answer

ikegami picture ikegami · Dec 4, 2012

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);