Variables and
Scoping
Randal L. Schwartz
Programs push data around. In Perl, this data lives in variables, and the
variables can be associated with various scopes. Let's take a look at Perl's
peculiar scoping rules.
To begin, let's define a term, lexical scope. A lexical scope provides
the boundaries of some property of the program associated with the text of the
program itself, as opposed to properties that are associated with the runtime
state of the program. Lexical properties might include variable declarations,
compiler directives, exceptions being caught, and so on.
In Perl, the largest lexical scope is the source file itself. Lexically scoped
items never affect anything larger than a file. Additionally, nearly all blocks
also introduce a nested lexical scope that ends where the block ends. Because
blocks are nested and not overlapping, the lexical scopes also nest. This will
become clearer in the examples that follow.
Some of the variables in a Perl program are package variables (also
called symbol-table variables). A package variable's full name consists
of a package prefix followed by the specific identifier for the variable. The
prefix is separated from the identifier by a double colon.
For example, in $Animal::count, Animal is the package prefix,
while count is the variable within the package. Both the package and
the identifier contain one or more alphanumerics and/or underscores. Additionally,
packages can have multiple, double-colon separated parts, as in $Animal::Dog::count.
Again, count is the variable, and Animal::Dog is the package prefix.
There's no necessary relationship between Animal and Animal::Dog,
although people tend to give related names to related packages.
|