why this is not a closure though ?
use warnings;
use strict;
{
my $a;
}
$a=1
print $a;
in my eyes my $a is visible outside the {} many thanks
First off, that's a bad example, because $a is a pre-defined global in perl, used by the built-in sort function. Secondly, when you declare a variable with "my", you are setting the scope of that variable to be the smallest block that encloses the declaration; or if it's not inside any curly-bracketed block, then the scope is the remainder of the given script file:
use strict;
use warnings;
$x = 0; # syntax error: $x has not been declared
my $y = 1; # ok, $y is "in scope" for remainder of file
{
my $y = 2; # a different $y, scope limited to this block
print $y, $/; # you cannot "see" the "outer" instance of $y
sub foo { $y--; print "the inner \$y is now $y\n"; }
foo();
}
print $y, $/; # this is the "outer" $y
my $x = 3; # ok: $x is in scope for remainder of file
my $y = 4; # warning: "my" declaration masks earlier declaration in
+same scope
print $y,$/;
foo();
As-is, that snippet will not run, but it will generate the error and warning messages shown in comments. Delete or comment-out the "$x=0" line, and it will run, but the "my $y=4" will still cause the warning about "masks earlier declaration in same scope".
When it runs, you'll see that the sub "foo", which is callable from anywhere, will always use the "inner" instance of $y, because that's the only one it could "see".
(updated to remove a stray ";", and to make the "foo" sub a little more interesting)
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, 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, 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.
|
|