New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Possible closure bug #689
Comments
From gross@klizix.mpi-stuttgart.mpg.deI am not sure if the following is really bug or just a feature In my opinion the output produced by 'func1' and 'func2' in the Greetings, Johannes Gross <<<<<<< cut <<<<<<<<<<<< my $count = 0; foreach (1..10) { $func1[ $count ] = sub { print "$count\n" }; $count++; $count++; # now $count == 11 foreach (@func1) { &$_ } print "\n"; foreach (@func2) { &$_ } <<<<<<< cut <<<<<<<<<<<< Output: 11 0 Perl Info
|
From @mjdominus
It's a feature that you don't understand.
Each time through the loop, a new $c variable is created, and then a However. $count is in an enclosing scope which is executed only once. This is exactly the behavior that closures are supposed to have. |
From @TimToadygross@klizx7.mpi-stuttgart.mpg.de writes: It's not a bug, actually. All the references to $count refer to the Larry |
From [Unknown Contact. See original ticket]
O.K., obviously I didn't correctly understood how closures work. Actually, I was relying on Sriram Srinivasan, who wrote in
Yes, may be in the second edition of 'Advanced Perl Programming'! Thank you very much for your fast reply, Johannes |
From @mjdominus
Sriram is mistaken, or perhaps oversimplifying. A closure doesn't Consider this: sub make_counter { $c = make_counter(); $c->('increment'); If $c were remembering the *value* that $n had when it was created, |
From @gsarOn Thu, 07 Oct 1999 14:17:18 EDT, Mark-Jason Dominus wrote:
Another way to think about it is that closures remember aliases Sarathy |
Migrated from rt.perl.org#1587 (status was 'resolved')
Searchable as RT1587$
The text was updated successfully, but these errors were encountered: