References to a File Handle

You can’t take a reference to a file handle—at least not directly. However, you can use a trick called a typeglob to do virtually the same thing. The syntax is

my $ref = \*FILE_HANDLE;

You can now use $ref as a file handle, for example:

my $ref = \*STDOUT; 
print $ref "Hello World\n";

So how is a typeglob different from a normal reference? The answer is the statement

my $ref = \*FOO;
makes $ref a sort of reference for all variables, no matter what type, whose name is FOO. Thus this statement also assigns %$ref the value of %FOO, $$ref is the same as $FOO, @$ref gets @FOO, and finally the subroutine FOO() is &$ref ...

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.