Name Lookups
So the question is, what’s in a name? How does Perl figure out what you
mean if you just say $bert? Glad
you asked. Here are the rules the Perl parser uses while trying to
understand an unqualified name in context:
First, Perl looks earlier in the immediately enclosing block to see whether the variable is declared in that same block with a
my,our, orstatedeclaration (see those entries in Chapter 27, as well as the section Scoped Declarations in Chapter 4). If there is amyorstatedeclaration, the variable is lexically scoped and doesn’t exist in any package—it exists only in that lexical scope (that is, in the block’s scratchpad). Because lexical scopes are unnamed, nobody outside that chunk of program can even name your variable.[46]If that doesn’t work, Perl looks for the block enclosing that block and tries again for a lexically scoped variable in the larger block. Again, if Perl finds one, the variable belongs only to the lexical scope from the point of declaration through the end of the block in which it is declared—including any nested blocks, like the one we just came from in step 1. If Perl doesn’t find a declaration, it repeats step 2 until it runs out of enclosing blocks.
When Perl runs out of enclosing blocks, it examines the whole compilation unit for declarations as if it were a block. (A compilation unit is just the entire current file, or the string currently being compiled by an
evalSTRINGoperator.) If the compilation unit is a file, that’s the ...
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