my creates variables only visible to the current scope, and the closures or blocks defined within it. A my variable is not available to anyone outside the scope, or anything called from within the scope, which was not declared inside it (and even so, that gets tricky).
Example:
my $var1;
$_ = '';
FOO: {
my $var2;
BAR: {
my $var3;
local $_ = 'bar set it';
&foo();
}
GORCH: {
my $var4;
}
}
sub foo {
my $var5;
print "$_\n";
}
Every scope in the above code can see $var1, because they were all declared under the main scope, in which $var1 was created. However, the main scope, and sub foo cannot see any variables declared within FOO: {}, and FOO: {} cannot see $var5, which was declared in sub foo. Furthermore, BAR: {} AND GORCH: {} can see everything except each other's private variables, and sub foo's $var5. sub foo, even when called from FOO: {}, BAR: {}, or GORCH: {} cannot see their private (my) variables. It can see
local versions of global (our, $_ sorts) variables though - sub foo, called from bar will print "bar set it".
You may also notice, if you
use Data::Dumper; print Dumper \%::; that any files you
do are also assigned a package, starting with "_<", and then the relative path. You may be able to use those. my experiments have been unsuccessful, but they weren't very thorough either.
Update: I forgot to mention that my and local both create new copies, and new variables, leaving anything with the same name on an outer scope untouched.
Also fixed HTML entity.
-nuffin
zz zZ Z Z #!perl
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.