in reply to Perl scoping not logical...?

Hmm, without going through it in detail, I think that Perl 5 doesn't support "closure cloning" like Perl 6. The closure is only made once, but you keep re-creating a variable closed over.

Replies are listed 'Best First'.
Re^2: Perl scoping not logical...?
by chromatic (Archbishop) on May 02, 2008 at 00:25 UTC

    I'm not sure that's entirely accurate, but I'm not certain I understand exactly what you mean.

    All Perl subroutines -- named or not -- get compiled during compile time into optrees accessed through an internal data structures called a CV. Named subroutines get stored in global symbol tables: hashes where the keys are the names of the subroutines and the values are CVs. Anonymous subroutines are stored elsewise (and I'm not certain enough of how to explain it well).

    CVs have arrays of lexpads attached. Lexpads store lexicals. There are multiple lexpads because any particular point in a program can have called through the same subroutine multiple times, and because lexical scopes nest.

    When you create a new closure at runtime, Perl doesn't recompile the code and create a new CV. It reuses the anonymous subroutine's CV, and attaches the current innermost lexpad. (In detail, there's probably a cloning operation here, but I don't want to get too much into the details.)

    This should be enough to explain why lexical variables won't stay shared.

      I think the point is that a named subroutine doesn't get the full closure treatment. It never "creates a new one at runtime" (called cloning in the Perl 6 synopses).

Re^2: Perl scoping not logical...?
by perl-diddler (Chaplain) on May 01, 2008 at 17:43 UTC
    Yeah...not my intent. I was trying for a non-closure, lexically scoped, named-function, but got stuck with the "if named(sub) then must be global", limitation in perl5 (maybe perl6 allows lexically scoped, *named* subs?)


    -linda

      Ah yes, writing a named sub in Perl 5 does not interact in the expected way with the context.

      In Perl 6, you can nest subs, no problem. They find the proper variable in their active caller, if you refer to one.