Book Home Programming PerlSearch this book

2.10. Typeglobs and Filehandles

Perl uses an special type called a typeglob to hold an entire symbol table entry. (The symbol table entry *foo contains the values of $foo, @foo, %foo, &foo, and several interpretations of plain old foo.) The type prefix of a typeglob is a * because it represents all types.

One use of typeglobs (or references thereto) is for passing or storing filehandles. If you want to save away a filehandle, do it this way:

$fh = *STDOUT;
or perhaps as a real reference, like this:
$fh = \*STDOUT;

This is also the way to create a local filehandle. For example:

sub newopen {
    my $path = shift;
    local *FH;          # not my() nor our()
    open(FH, $path) or return undef;
    return *FH;         # not \*FH!
}
$fh = newopen('/etc/passwd');
See the open function for other ways to generate new filehandles.

The main use of typeglobs nowadays is to alias one symbol table entry to another symbol table entry. Think of an alias as a nickname. If you say:

*foo = *bar;
it makes everything named "foo" a synonym for every corresponding thing named "bar". You can alias just one variable from a typeglob by assigning a reference instead:
*foo = \$bar;
makes $foo an alias for $bar, but doesn't make @foo an alias for @bar, or %foo an alias for %bar. All these affect global (package) variables only; lexicals cannot be accessed through symbol table entries. Aliasing global variables like this may seem like a silly thing to want to do, but it turns out that the entire module export/import mechanism is built around this feature, since there's nothing that says the symbol you're aliasing has to be in your namespace. This:
local *Here::blue = \$There::green;
temporarily makes $Here::blue an alias for $There::green, but doesn't make @Here::blue an alias for @There::green, or %Here::blue an alias for %There::green. Fortunately, all these complicated typeglob manipulations are hidden away where you don't have to look at them. See the sections Section 2.2.4, "Handle References" and Section 2.2.5, "Symbol Table References" in Chapter 8, "References", the section Section 2.1, "Symbol Tables" in Chapter 10, "Packages", and Chapter 11, "Modules", for more discussion on typeglobs and importation.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.