http://www.perlmonks.org?node_id=95971


in reply to Unusual Closure Behaviour

First, neither of those are closures. They are both examples of static variables and named functions. The term "closure" refers to a code reference that also carries along some variables. In neither of these case is the $x being carried around in a code reference (in part because no code references are being used).

Second, I (if anyone cares) don't consider my $x if 0; to be a good thing to actually use. A while back I had an idea to allow BEGIN to be a statement modifier just like for, while, if, etc. Then you could implement static variables like:

sub foo { my $x= 'a' BEGIN; return ++$x; }
which has the benefit of allowing you to initialize your static vars and of cluing you into the fact that the initialization happens at compile time so you can't use anything that isn't available yet.

This feature would have other nifty uses. For example: my $haveCGI= eval { require CGI }   BEGIN; But the one that could be really fun would be: eval "my $ARGV[0];"   BEGIN; if you could stop eval from implying an enclosing scope. This could be very powerful and give TheDamian lots of new ways to do really scary things in Perl. (:

        - tye (but my friends call me "Tye")