AcornSearch - Acorn and RISC OS information searching
RISC OS Search
containing
"Nutty quip goes here!"
Home  |  About  |  Filebase Archive  |  StrongHelp Manuals  |  Newsgroups  |  Module Database
my EXPR

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

my $_;      # Illegal.

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.  See perlref.)

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:

sub RANGEVAL {
my($min, $max, $thunk) = @_;
my $result = '';
my $i;


for ($i = $min; $i < $max; $i++) {
$result .= eval $thunk;
}

$result;
}



if ($sw eq '™v') {
my @ARGV = @ARGV;
unshift(@ARGV,'echo');
system @ARGV;
}

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

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

both supply a list context to the righthand side, while

my $foo = <STDIN>;

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

my $foo, $bar = 1;

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 the 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.

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

use strict 'vars';

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 "no strict 'vars'".


[sh-index] Back to list of manuals