Chapter 8. Symbol Tables and Typeglobs
Although I don’t normally deal with typeglobs or the symbol table, I need to understand them for the tricks I’ll use in later chapters. I’ll lay the foundation for advanced topics including dynamic subroutines and jury-rigging code in this chapter.
Symbol tables organize and store Perl’s package (global) variables, and I can affect the symbol table through typeglobs. By messing with Perl’s variable bookkeeping I can do some powerful things. You’re probably already getting the benefit of some of these tricks without evening knowing it.
Package and Lexical Variables
Before I get too far, I want to review the differences between package and lexical variables. The symbol table tracks the package variables, but not the lexical variables. When I fiddle with the symbol table or typeglobs, I’m dealing with package variables. Package variables are also known as global variables since they are visible everywhere in the program.
In Learning Perl and Intermediate
Perl, we used lexical variables whenever possible. We declared
lexical variables with my and those
variables could only be seen inside their scope. Since lexical variables
have limited reach, I didn’t need to know all of the program to avoid a
variable name collision. Lexical variables are a bit faster too since Perl
doesn’t have to deal with the symbol table.
Lexical variables have a limited scope, and they only affect that part of the program. This
little snippet declares the variable name $n twice ...
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