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

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.

The typeglob was an early method for creating references before real references were put in the language. Although it has been made obsolete by better references, in most cases, it still is useful when it comes to file handle references.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset