Controlling the Use of Globals
Another commonly seen declaration is the strict pragma, which has several functions, one of which is
to control the use of global variables. Normally, Perl lets you
create new globals (or, all too often, step on old globals) just by
mentioning them. No variable declarations are necessary—by default,
that is. Because unbridled use of globals can make large programs or
modules painful to maintain, you may sometimes wish to discourage
their accidental use. As an aid to preventing such accidents, you
can say:
use v5.14; # Turn on strict implicitly. use strict "vars"; # Turn on strict explicitly.
This means that any variable mentioned from here to the end of
the enclosing scope must refer either to a lexical variable declared
with my, state, or our, or to an explicitly allowed global.
If it’s not one of those, a compilation error results. A global is
explicitly allowed if one of the following is true:
It’s one of Perl’s program-wide special variables (see Chapter 25).
It’s fully qualified with its package name (see Chapter 10).
It’s imported into the current package (see Chapter 11).
It’s masquerading as a lexically scoped variable via an
ourdeclaration. (This is the main reason we addedourdeclarations to Perl.)
Of course, there’s always the fifth alternative—if the pragma proves burdensome, simply countermand it within an inner block using:
no strict "vars";
You can also turn on strict checking of symbolic dereferences and accidental use of barewords with this ...
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