| ACADEMIC COMPUTING and COMMUNICATIONS CENTER | ||||||||
| |||||||||||||||||||||
Typeglobs | |||||||||||||||||||||
|
Typeglobs are much less useful to users now that perl has references. But they are still used in old code, and occasionally they are needed to deal with passing filehandles or to alias the dereferencing of references. At least you should recognize them, even if you don't use them much. |
|||||||||||||||||||||
| Typeglobs | |||||||||||||||||||||
|
A typeglob is a perl data type. It is a mini-table that provides indirection between an identifier, such as var, and the actual data structures used for $var, @var, %var, &var and so forth. The identifier exists in a symbol table (per package). The typeglob lets the user modify the indirection between that identifier and the real data structures. Typeglobs can be used as ordinary variables, with the special prexix *. *b = *a; # assignment of typeglobs $a = "pizza"; print $b; # pizza Note: typeglobs only work with global (or package local) variables. They have nothing to do with my() variables. |
|||||||||||||||||||||
| Relation to References | |||||||||||||||||||||
|
Typeglobs can interact with references. If you assign a reference to a typeglob, only that variable gets aliased. @a = qw(I am A); @b = qw(I am B); $a = 'A'; $b = 'B'; *b = \$a; # assign only scalar print $b; # A print "@b"; # I am B |
|||||||||||||||||||||
| Examples | |||||||||||||||||||||
|
Suppose you want to pass a filehandle to a subroutine.
open (F ">filename");
do_it (*F);
sub do_it {
local *G = shift; # not my() !
print G "stuff from do_it";
}
Suppose you want to pass multiple hashes or arrays to a subroutine. You need to pass references. But if you don't want to remember to dereference each one each time you use it, use typeglobs.
do_it (\@array, \%hash);
sub do_it {
local( *a, *h) = @_;
print a[0], keys %h, "\n";
}
Typeglobs can be used to alias subroutines. In fact, you can redefine existing subroutines, or you can choose the subroutine name at runtime.
*salt = \&pepper;
salt(); # calls pepper()
$season = "cayenne";
*$season = sub { ... }
cayenne(); # calls {...}
|
|||||||||||||||||||||
| Perl II | Previous: 6. Ties & DBM | Next: 8. CGI |
| 1999-3-3 BobG |
|