in reply to closure clarity, please
You seem to believe that subs are scoped to the block that contain them. That's not true. Subs are global.
Based on vitoco's example and JadeNB's analysis, I believe that statement should now be considered false. There appears to be two facets of scope that subs demonstrate. On the one hand, no matter where a sub is defined, it can be called anywhere in your program. In that sense, a sub has global scope.
On the other hand, the variables that a sub can see depends on the scope in which the sub is defined. In that sense, a sub has local scope.
Here is a simplified version of vitoco's example:
use strict; use warnings; use 5.010; my $val = 10; sub f { say "in global f, \$val is: $val"; } f(); #Demonstrates that the global definition of f is overwritten #by the local definition of f (below) at compile time. As a #result, you won't see output from global f. When the local f #executes instead, the global $val above is hidden by a local #$val in the definition of f (below). say '=' x 20; sub g { my $val = shift; say "in g, \$val is: $val"; #This definition of f closes over $x in previous line. sub f { #line 40 say "in local f, \$val is: $val"; } f(); } g('hello'); say '=' x 20; g('goodbye'); say '=' x 20; --output:-- Variable "$val" will not stay shared at 4perl.pl line 41. Subroutine f redefined at 4perl.pl line 40. Use of uninitialized value $val in concatenation (.) or string at 4per +l.pl line 41. in local f, $val is: ==================== in g, $val is: hello in local f, $val is: hello ==================== in g, $val is: goodbye in local f, $val is: hello ====================
If a sub truly had global scope, then the local $val would have no affect on the locally defined sub. Instead, the sub would have closed over the global $val, and changes to the local $val would not be seen by the sub.
*Yes, I know that "local $val" and "global $val" are really my variables. However, referring to them as "the my variable $val that was defined in the same block as the nested sub definition" or "the my variable $val declared outside of any blocks" is too unwieldy."
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: closure clarity, please
by ikegami (Patriarch) on Nov 27, 2009 at 01:58 UTC | |
by 7stud (Deacon) on Nov 27, 2009 at 03:04 UTC | |
by ikegami (Patriarch) on Nov 27, 2009 at 03:14 UTC |