develooper Front page | perl.perl6.language | Postings from August 2001

Re: explicitly declare closures???

Thread Previous | Thread Next
Ken Fox
August 28, 2001 05:47
Re: explicitly declare closures???
Message ID:
Dave Mitchell wrote:
> The whole point is that closed variables *aren't* 'just local variables'.
> The inner $x's in the following 2 lines are vastly different:
> sub foo { my $x= ...     { $x } ....}
> sub foo { my $x= ... sub { $x } ....}

You really need to learn what a closure is. There's a very nice book
called "Structure and Interpretation of Computer Programs" that can
give you a deep understanding. **

Anyways, it's important to understand that closures do not change the
scoping rules. A closure simply *captures* an existing environment.
If the environment isn't captured properly or changes after capture,
then you have buggy closures.

> causes the behaviour to change is that the middle $x implicitly gives
> foo() a copy of $x at compile time. When the anon sub is cloned,
> it picks up the current value of foo()'s $x. Without the middle $x, the
> cloned sub picks up the outer $x instead.

You're speaking in Perl implementation terms. I've already told you
that if Perl acts the way you say it does, then Perl has buggy
closures. You don't need to explain a bug to know that one exists!

On page 260 in "Programming Perl" (3rd ed), Larry/Tom/Jon talk about
how Perl's closures (should) behave:

  In other words, you are guaranteed to get the same copy of
  a lexical variable each time ...

IMHO bugs in Perl 5 shouldn't carry over to Perl 6. (Unless, of course,
we *like* the bugs... ;)

- Ken

** Unfortunately the term closure has two important meanings that
are not really related. We're talking about closing a subroutine's
environment, which is not how SICP uses the word. If you want a
"Closures For 21 Dummies" sort of book, this is not it.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About