Making Variables Private to a Function
Problem
Your subroutine needs temporary variables. You shouldn’t use global variables, because another subroutine might also use the same variables.
Solution
Use my
to declare a variable private to a region
of your program:
sub somefunc { my $variable; # $variable is invisible outside somefunc() my ($another, @an_array, %a_hash); # declaring many variables at once # ... }
Discussion
The my
operator confines a variable to a
particular region of code in which it can be used and accessed.
Outside that region, it can’t be accessed. This region is
called its scope.
Variables declared with my
have lexical
scope
, which means that they exist only within
a particular textual area of code. For instance, the scope of
$variable
in the Solution is the function it was
defined in, somefunc
. When a call to
somefunc
is made, the variable is created. The
variable is destroyed when the function call ends. The variable can
be accessed within the function, but not outside of it.
A lexical scope is usually a block of code with a set of braces
around it, such as those defining the body of the
somefunc
subroutine or those marking the code
blocks of if
, while
,
for
, foreach
, and
eval
statements. Lexical scopes may also be an
entire file or strings given to eval
. Since a lexical scope is usually a block, we’ll sometimes talk about lexical variables (variables with lexical scope) being only visible in their block when we mean that they’re only visible in their scope. Forgive ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.