Private and Local Variables
Any variables you use in the function that aren’t declared private are global variables. In subroutines, you’ll often want to use variables that won’t be used anywhere else in your program, and you don’t want them taking up memory when the subroutine is not being executed. You also might not want to alter variables in subroutines that might have the same name as global variables.
The my
function
declares variables that are lexically scoped
within the subroutine. Lexically scoped variables are private
variables that exist only within the block or subroutine in which
they are declared. Outside of their scope, they are invisible and
can’t be altered in any way.
To scope multiple variables at once, use a list in
parentheses. You can also assign a variable in a my
statement:
my @list = (44, 55, 66); my $cd = "orb";
Dynamic variables are visible to other subroutines
called from within their scope, are defined with local
, and are not private variables but
global variables with temporary values. When a subroutine is
executed, the global value is hidden away, and the local value is
used. Once the scope is exited, the original global value is used.
Most of the time, you will want to use my
to localize parameters in a
subroutine.
Get Perl in a Nutshell, 2nd Edition 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.