The perl documentation (perldoc -f my) has this to say about the perl
builtin "my":
A my declares the listed variables to be local (lexically) to the
enclosing block, file, or eval. If more than one value is listed, the
list must be placed in parentheses. See Private Variables via my() in
the perlsub manpage for details.
The section on lexical scoping it refers to is an excellent explanation,
but I'll try to add the way I think of it just because...
The english meaning of "my" is a rather possesive one. It means that
this thing here belongs to ME and almost more importantly, not to you.
It's not ours (or I would have said it was), and the ownership of this
thing is not abmiguous. It's mine - and mine only. My accomlishes the
same thing in perl.
Andy Says 'My Apple' #declares that is is an apple, and that it belongs
to this Andy
my Foo; # pre-declares this as a lexically scoped variable belonging to
the part of the program that called it.
What my does, is tell perl how much of the program has that particular
variable. Consider the following:
$variable = "Apple\n"
foreach (0 .. 9) {
$variable = "orange\n";
print $variable;
}
print $variable;
The above code will print out 11 lines of "orange", because when you
change the value of $variable within the foreach loop, you're changing
the value. By default, variables attempt to be global in perl.
now let's play with
my $variable = "Apple\n";
foreach (0 .. 9) {
my $variable = "orange\n";
print $variable;
}
print $variable;
The second example there will print our 10 lines of "Orange" followed by
one of "Apple". The reason for this is that the variable which is set
outside the block of code run by the foreach loop is now a completely
different variable from the one set inside the block of code run by the
foreach loop. The use of "my" tells perl that while the main block of
the program owns a variable called $variable, the foreach loop owns a
completely different variable, which just co-incidentally also happens
to be named $variable.
The possesiveness of the word is retained in perl. My scopes a variable
to the block of code in which it is declared.
Of course none of this would be complete without mentioning that the
newly introduced keyword "our" is equally as permissive in perl as it is
in the english language ;)
Hope that helps.
--A
SunDog wrote:
> Hello everyone,
>
> I'm new to PERL ...
> and have a question about a style/format I've observed
> where 'my' is placed in front of arrays, hashes - you name it ...
> At first I interpreted this as a Nemonic name but several
> functions might have this in the same code .. what gives ?
>