develooper Front page | perl.perl5.porters | Postings from November 2010

Re: [perl #79908] my $x; sub(){$x} makes a constant even if $x changes

Thread Previous | Thread Next
Eirik Berg Hanssen
November 30, 2010 09:50
Re: [perl #79908] my $x; sub(){$x} makes a constant even if $x changes
Message ID:
On Tue, Nov 30, 2010 at 6:37 PM, Reini Urban <> wrote:

> Zefram schrieb:
>  Dave Mitchell wrote:
>>> What do you think is the bug? It seems to be behaving the way I expect.
>> The code looks like it closes over the lexical variable $x.  That lexical
>> variable is then set to 6, so when the closure is later called (through
>> the&foo name) it would be expected for it to return 6.  This is how
>> closures normally work, both in other languages, and in Perl when that
>> particular form with the () prototype is not used.  For the closure
>> operation to return a constant-5 sub cannot be justified by reference
>> to closure theory; it can only be explained as a special exception in
>> Perl semantics, which is what it is.
> Sorry, I don't understand that special theory of yours.
> Why on earth should
>  BEGIN{my $x = 5; *foo = sub(){$x}; $x=6} print foo'
> ever print 6 again?


    BEGIN{my $x = 5; *foo = sub(){$x;$x}; $x=6} print foo


> We are using lexical scope, not dynamic scope.
> With dynamic scoping, i.e. local $x = 5; you could justify a 6.
> Is it really that perl coders still cannot understand the difference
> between lexical and dynamic scope?

  Not in this case.  We are expecting the subroutine to close over the
lexical variable, as subroutines tend to ...


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