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)