Accessing the Symbol Table

Perl has a number of features that permit introspection, chief among them the ability to get information about the contents of the symbol table. This property is sometimes called reflection or introspection.

Reflection makes it easy to write system-level tools such as debuggers and profilers. We will also use this property in Chapter 11, to develop a module that can transparently dump an object’s data to a file or a database (and subsequently restore it) without having to write any application-specific code.

We saw earlier in this chapter that each package gets its own symbol table (also called stash , short for “symbol table hash”). Perl makes these stashes available as regular associative arrays. The stash for a package named Foo can be accessed by using the hash called %Foo::. The main package is available as %main::, or simply as %::. In fact, all other packages’ hash tables are available from the main stash (%main:: hence points to itself), as illustrated in Figure 6.1.

Packages’ stashes are available in main’s namespace

Figure 6-1. Packages’ stashes are available in main’s namespace

Iterating through the all the symbolic names inside a package is simple:

foreach $name (keys %main::) {
    print "$name, \n"; 
}

As we saw earlier, each of these symbolic names maps to a typeglob, which itself points to one or more values (one or more of each type: scalar, array, hash, subroutine, filehandle, format name, or directory ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.