Passing a File Handle to a Subroutine

To pass a file handle to a subroutine, use * in the subroutine prototype type to indicate a file handle parameter. But getting the file handle into something you can use is a little tricky. For that, you need a module called Symbol:

use Symbol; 

sub print_it(*) 
{
    my $file_handle = qualify_to_ref(shift, caller);

You can now use this file handle in a print statement just like a normal Perl file handle:

print $file_handle "Hello World\n";

Remember that there is no comma after the file handle.

To call this function, just put the file handle in the parameter list:

print_it(STDOUT);

You must use a module because Perl treats file handles differently from other variables. When you specify STDOUT in the parameter, ...

Get Perl for C Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.