Re: Interesting behaviour with lexical variable



"jl_post@xxxxxxxxxxx" <jl_post@xxxxxxxxxxx> wrote:
anno4000@xxxxxxxxxxxxxxxxxxxxxx wrote:

while (my $input = <STDIN>){
my $num = abs $input;
my $add = sub {
$num + $num;
};
# sub add { $num + $num }
print $add->(), "\n";

}

Note that $num in the loop is *not* the same variable each time,
as printing the ref shows. The named sub add() firmly believes
in the very first variable named $num (and its value) while the
loop advances and uses a new one every time. A closure knows
about the changes.

I wouldn't think that a closure knows about the changes. That
closure only knows about the changes because a new closure gets created
each time through the loop (each time using a new value of $num).

But define the closure only once and it will always use the value of
$num that it had the first time through the loop:

my $add;
while (my $input = <STDIN>){
my $num = abs $input;
$add = sub {
$num + $num;
} unless defined $add;
print $add->(), "\n";
}

With this code, the $add only get assigned a closure once, and keeps
the first value of $num each time.

Furthermore, if you define the named sub in a string eval, so that it is
recompiled each time, it will behave like the non-stultified anonymous
closure does.

Xho

--
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service $9.95/Month 30GB
.



Relevant Pages