in reply to Re: Why are closures cool?
in thread Why are closures cool?

Are you sure?
screamer@home:~$ cat test.pl use warnings; use strict; { my $i = 0; sub test { print ++$i, @_ } } test "\n" for 1..10; screamer@home:~$ perl -c test.pl test.pl syntax OK screamer@home:~$ perl -v This is perl, v5.6.0 built for i386-linux ...
Doesn't look broken to me. (It executes with no warnings too, in case anyone's wondering.)

Am I missing something?

Replies are listed 'Best First'.
Re: Re: Re: Why are closures cool?
by runrig (Abbot) on Jan 12, 2002 at 22:13 UTC
    Doesn't look broken to me... Am I missing something?

    The 'brokenness' comes when you have a named sub inside another subroutine. If you try this:

    use strict; use warnings; sub function { my $i = 0; sub test { print ++$i,"\n"; } test(); test(); }
    You'll get a "variable will not stay shared" warning, and will not get the results you expect. This happens alot with Apache::Registry novices because people will write subroutines with global (i.e. my variables at the outermost scope) variables, and Apache::Registry wraps the entire script into a subroutine of its own, so you end up with a situation like the above (the answer being to not use globals, or put the subroutines and their globals into a package of their own).
      Oh. Well named subroutines always go into the "package scope" (is there a proper term for this?), so that code corresponds to
      use strict; use warnings; sub test { print ++$i,"\n"; } sub function { my $i = 0; test(); test(); }
      regardless of what you meant it to.

      And to be honest, I can live with that. I don't see much of a point to using named subsubroutines - unless you want to pass it around as a reference, in which case you didn't do anything less than you would have had to with an anonymous sub. Right? Of course it is correct to point out that Perl's closures are not exactly equivalent to what is commonly referred to as a closure. (Though I think whether that makes them incomplete is debatable.)
        What is correct?

        I had never before heard the accusation that Perl closures are not what is normally considered a closure. The issue that runrig pointed out is that trying to mix the semantics of package names with closures allows situations which cannot be resolved properly. But use closures around anonymous functions and things work perfectly well.

        Do you have a specific example of how Perl's closures should do something other than what they do?