A "my" declares the listed variables to be local (lexically) to the enclosing block, subroutine, eval or "do". If more than one value is listed, the list must be placed in parens. All the listed elements must be legal lvalues. Only alphanumeric identifiers may be lexically scoped--magical builtins like $/ must be localized with "local" instead. In particular, you're not allowed to say
Unlike the "local" declaration, variables declared with "my" are totally hidden from the outside world, including any called subroutines (even if it's the same subroutine--every call gets its own copy).
(An eval() , however, can see the lexical variables of the scope it is being evaluated in so long as the names aren't hidden by declarations within the eval() itself.)
The EXPR 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 an undefined value.) Commonly this is used to name the parameters to a subroutine. Examples:
The "my" is simply a modifier on something you might assign to. So when you do assign to the EXPR, the "my" doesn't change whether EXPR is viewed as a scalar or an array. So
both supply a list context to the righthand side, while
supplies a scalar context. But the following only declares one variable:
That has the same effect as
The declared variable is not introduced (is not visible) until after the current statement. Thus,
can be used to initialize the new $x with the value of the old $x, and the expression
is false unless the old $x happened to have the value 123.
Some users may wish to encourage the use of lexically scoped variables. As an aid to catching implicit references to package variables, if you say
then any variable reference from there to the end of the enclosing block must either refer to a lexical variable, or must be fully qualified with the package name. A compilation error results otherwise. An inner block may countermand this with S<"no strict 'vars'">.