Re: Interesting behaviour with lexical variable
- From: xhoster@xxxxxxxxx
- Date: 30 Oct 2006 21:03:45 GMT
"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
.
- References:
- Interesting behaviour with lexical variable
- From: Ferry Bolhar
- Re: Interesting behaviour with lexical variable
- From: jl_post@xxxxxxxxxxx
- Re: Interesting behaviour with lexical variable
- From: anno4000
- Re: Interesting behaviour with lexical variable
- From: jl_post@xxxxxxxxxxx
- Interesting behaviour with lexical variable
- Prev by Date: Re: backup via ftp, depth copy, script already out there?
- Next by Date: loop over a string to do search/replacement using regexp?
- Previous by thread: Re: Interesting behaviour with lexical variable
- Next by thread: Re: Interesting behaviour with lexical variable
- Index(es):
Relevant Pages
|