Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Closures clarification

by graff (Chancellor)
on Dec 04, 2007 at 13:46 UTC ( #654787=note: print w/replies, xml ) Need Help??


in reply to Closures clarification

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)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://654787]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2021-02-24 21:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?