Scoped Variable Declarations
Most of the rest of this chapter is about using global variables. Or, rather, it’s about not using global variables. There are various declarations that help you not use global variables—or, at least, not use them foolishly.
We already mentioned the package declaration, which was introduced
into Perl long ago to allow globals to be split up into separate
packages. This works pretty well for certain kinds of variables.
Packages are used by libraries, modules, and classes to store their
interface data (and some of their semiprivate data) to avoid
conflicting with variables and functions of the same name in your
main program or in other modules. If you see someone write $Some::stuff,[81] he’s using the $stuff scalar variable from the package
Some. See Chapter 10.
If this were all there were to the matter, Perl programs would
quickly become unwieldy as they got longer. Fortunately, Perl’s
three scoping declarators make it easy to create completely private
variables (using my or state), or to give selective access to
global ones (using our). There is
also a pseudodeclarator to provide temporary values to global variables
(using local). These declarators
are placed in front of the variable in question:
my $nose; our $House; state $troopers = 0; local $TV_channel;
If more than one variable is to be declared, the list must be placed in parentheses:
my ($nose, @eyes, %teeth); our ($House, @Autos, %Kids); state ($name, $rank, $serno); local (*Spouse, $phone{HOME}); ...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