Typeglobs and Filehandles
Perl uses a 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, which was especially popular before Perl had filehandle references. If you want to save away a bareword filehandle, do it this way:
$fh = *STDOUT;
or perhaps as a real reference, like this:
$fh = \*STDOUT;
or perhaps accessing the filehandle portion in that symbol table entry:
$fh = *STDOUT{IO};This used to be the preferred way to create a local filehandle. For example:
sub newopen {
my $path = shift;
local *FH; # not my() nor our()
open(FH, '<', $path) || return undef;
return *FH; # not \*FH!
}
$fh = newopen("/etc/passwd");These days, however, it’s almost always better to let Perl pick a filehandle and fill in an empty variable for you:
sub newopen {
my $path = shift;
open(my $fh, '<', $path) || return undef;
return $fh;
}
$fh = newopen("/etc/passwd");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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access