- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

8.1 Private Variables via my()


my $foo;            # declare $foo lexically local
my (@wid, %get);    # declare list of variables local
my $foo = "flurp";  # declare $foo lexical, and init it
my @oof = @bar;     # declare @oof lexical, and init it
my $x : Foo = $y;   # similar, with an attribute applied

WARNING: The use of attribute lists on my declarations is still evolving. The current semantics and interface are subject to change. See "Get/set subroutine or variable attributes" (attributes) in the Perl Library Reference Manual (Volume 1) and "Simpler definition of attribute handlers" (Attribute::Handlers) in the Perl Library Reference Manual (Volume 2).

The my operator declares the listed variables to be lexically confined to the enclosing block, conditional (if/unless/elsif/else), loop (for/foreach/while/until/continue), subroutine, eval, or do/require/use'd file. If more than one value is listed, the list must be placed in parentheses. All listed elements must be legal lvalues. Only alphanumeric identifiers may be lexically scoped--magical built-ins like $/ must currently be localized with local instead.

Unlike dynamic variables created by the local operator, lexical variables declared with my are totally hidden from the outside world, including any called subroutines. This is true if it's the same subroutine called from itself or elsewhere--every call gets its own copy.

This doesn't mean that a my variable declared in a statically enclosing lexical scope would be invisible. Only dynamic scopes are cut off. For example, the bumpx() function below has access to the lexical $x variable because both the my and the sub occurred at the same scope, presumably file scope.

my $x = 10;
sub bumpx { $x++ }

An eval(), however, can see lexical variables of the scope it is being evaluated in, so long as the names aren't hidden by declarations within the eval() itself. See 15.

The parameter list to my() may be assigned to if desired, which allows you to initialize your variables. (If no initializer is given for a particular variable, it is created with the undefined value.) Commonly this is used to name input parameters to a subroutine. Examples:

   $arg = "fred";        # "global" variable
   $n = cube_root(27);
   print "$arg thinks the root is $n\n";
fred thinks the root is 3
   sub cube_root {
       my $arg = shift;  # name doesn't matter
       $arg **= 1/3;
       return $arg;

The my is simply a modifier on something you might assign to. So when you do assign to variables in its argument list, my doesn't change whether those variables are viewed as a scalar or an array. So

my ($foo) = <STDIN>;                # WRONG?
my @FOO = <STDIN>;

both supply a list context to the right-hand side, while

my $foo = <STDIN>;

supplies a scalar context. But the following declares only one variable:

my $foo, $bar = 1;                  # WRONG

That has the same effect as

my $foo;
$bar = 1;

The declared variable is not introduced (is not visible) until after the current statement. Thus,

my $x = $x;

can be used to initialize a new $x with the value of the old $x, and the expression

my $x = 123 and $x == 123

is false unless the old $x happened to have the value 123.

Lexical scopes of control structures are not bounded precisely by the braces that delimit their controlled blocks; control expressions are part of that scope, too. Thus in the loop

while (my $line = <>) {
    $line = lc $line;
} continue {
    print $line;

the scope of $line extends from its declaration throughout the rest of the loop construct (including the continue clause), but not beyond it. Similarly, in the conditional

if ((my $answer = <STDIN>) =~ /^yes$/i) {
} elsif ($answer =~ /^no$/i) {
} else {
    chomp $answer;
    die "'$answer' is neither 'yes' nor 'no'";

the scope of $answer extends from its declaration through the rest of that conditional, including any elsif and else clauses, but not beyond it. See 4.3 for information on the scope of variables in statements with modifiers.

The foreach loop defaults to scoping its index variable dynamically in the manner of local. However, if the index variable is prefixed with the keyword my, or if there is already a lexical by that name in scope, then a new lexical is created instead. Thus in the loop

for my $i (1, 2, 3) {

the scope of $i extends to the end of the loop, but not beyond it, rendering the value of $i inaccessible within some_function().

Some users may wish to encourage the use of lexically scoped variables. As an aid to catching implicit uses to package variables, which are always global, if you say

use strict 'vars';

then any variable mentioned from there to the end of the enclosing block must either refer to a lexical variable, be predeclared via our or use vars, or else must be fully qualified with the package name. A compilation error results otherwise. An inner block may countermand this with no strict 'vars'.

A my has both a compile-time and a run-time effect. At compile time, the compiler takes notice of it. The principal usefulness of this is to quiet use strict 'vars', but it is also essential for generation of closures as detailed in 15. Actual initialization is delayed until run time, though, so it gets executed at the appropriate time, such as each time through a loop, for example.

Variables declared with my are not part of any package and are therefore never fully qualified with the package name. In particular, you're not allowed to try to make a package variable (or other global) lexical:

my $pack::var;      # ERROR!  Illegal syntax

In fact, a dynamic variable (also known as package or global variables) are still accessible using the fully qualified :: notation even while a lexical of the same name is also visible:

package main;
local $x = 10;
my    $x = 20;
print "$x and $::x\n";

That will print out 20 and 10.

You may declare my variables at the outermost scope of a file to hide any such identifiers from the world outside that file. This is similar in spirit to C's static variables when they are used at the file level. To do this with a subroutine requires the use of a closure (an anonymous function that accesses enclosing lexicals). If you want to create a private subroutine that cannot be called from outside that block, it can declare a lexical variable containing an anonymous sub reference:

my $secret_version = '1.001-beta';
my $secret_sub = sub { print $secret_version };

As long as the reference is never returned by any function within the module, no outside module can see the subroutine, because its name is not in any package's symbol table. Remember that it's not REALLY called $some_pack::secret_version or anything; it's just $secret_version, unqualified and unqualifiable.

This does not work with object methods, however; all object methods have to be in the symbol table of some package to be found. See 15.7 for something of a work-around to this.

ISBN 9781906966027Perl Language Reference ManualSee the print edition