Symbol Tables

The contents of a package are collectively called a symbol table. Symbol tables are stored in a hash whose name is the same as the package, but with two colons appended. The main symbol table’s name is thus %main::. Since main also happens to be the default package, Perl provides %:: as an abbreviation for %main::.

Likewise, the symbol table for the Red::Blue package is named %Red::Blue::. As it happens, the main symbol table contains all other top-level symbol tables, including itself, so %Red::Blue:: is also %main::Red::Blue::.

When we say that a symbol table “contains” another symbol table, we mean that it contains a reference to the other symbol table. Since main is the top-level package, it contains a reference to itself, making %main:: the same as %main::main::, and %main::main::main::, and so on, ad infinitum. It’s important to check for this special case if you write code that traverses all symbol tables.

Inside a symbol table’s hash, each key/value pair matches a variable name to its value. The keys are the symbol identifiers, and the values are the corresponding typeglobs. So when you use the *NAME typeglob notation, you’re really just accessing a value in the hash that holds the current package’s symbol table. In fact, the following have (nearly) the same effect:

*sym = *main::variable;
*sym = $main::{"variable"};

The first is more efficient because the main symbol table is accessed at compile time. It will also create a new typeglob by that name if none previously ...

Get Programming Perl, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.