Lexically Scoped Variables: my
To help you avoid the maintenance headaches of global
variables, Perl provides lexically scoped variables, often
called lexicals for short. Unlike
globals, lexicals guarantee you privacy. Assuming you don’t hand out
references to these private variables that would let them be fiddled
with indirectly, you can be certain that every possible access to
these private variables is restricted to code within one discrete
and easily identifiable section of your program. That’s why we
picked the keyword my, after
all.
A statement sequence may contain declarations of lexically
scoped variables. Such declarations tend to be placed at the front
of the statement sequence, but this is not a requirement; you may
simply decorate the first use of a variable with a my declarator wherever it occurs (as long
as it’s in the outermost scope the variable is used). In addition to
declaring variable names at compile time, the declarations act like
ordinary runtime statements: each of them is executed within the
sequence of statements as if it were an ordinary statement without
the declarator:
my $name = "fred";
my @stuff = ("car", "house", "club");
my ($vehicle, $home, $tool) = @stuff;These lexical variables are totally hidden from the world
outside their immediately enclosing scope. Unlike the dynamic
scoping effects of local (see below), lexicals are hidden from any subroutine called from their scope. This is true even if the same subroutine is called from itself or elsewhere—each ...
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