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
From:
Eric Brine
Date:
November 30, 2010 10:10
Subject:
Re: [perl #79908] my $x; sub(){$x} makes a constant even if $x changes
Message ID:
AANLkTinDfh_s_1fewmcGJj72_aLrDC=xFEQ8gzCD5DES@mail.gmail.com
On Tue, Nov 30, 2010 at 12:37 PM, Reini Urban <rurban@x-ray.at> wrote:

> 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?
>
> We are using lexical scope, not dynamic scope.
> With dynamic scoping, i.e. local $x = 5; you could justify a 6.
>

Closures capture variables, not values. (At least in Perl. I don't know
about elsewhere.) The variable can freely be changed.

Given the following body of code,

{
   set(123);
   say(get());
}

Observe the differences depending on how those functions are defined.

BEGIN { # Works
   my $private;
   sub get()  { $private }
   sub set($) { $private = $_[0]; }
}

BEGIN { # Doesn't work
   my $private;
   *get = sub()  { $private };
   *set = sub($) { $private = $_[0]; };
}

BEGIN { # Works
   my $private;
   *get = sub    { $private };
   *set = sub($) { $private = $_[0]; };
}

This has nothing to do with dynamic scope. Dynamic scoping would allow get()
and set() to see a variable that resides their caller.

- Eric

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About