Re: Interesting behaviour with lexical variable
- From: "Ferry Bolhar" <bol@xxxxxxxxxxxxxxxxx>
- Date: Tue, 31 Oct 2006 10:51:36 +0100
Michele Dondi:
print '[anon]';
print &$_ for
map { my $x=$_; sub () { $x } }
qw/foo bar baz/;
In this code, "sub" acts as an _operator_ and therefore
is evaluated for every loop iteration at run-time, yielding
a new value for $x each time.
print '[named]';
print &$_ for
map { my $x=$_; sub foo () { $x }; \&foo }
qw/foo bar baz/;
In this code, "sub" acts as a _declarator_, getting
evaluated only once because the function declaration
is processed at compile time. Therefore, the first value
for $x will be retained. It's jst another kind of loop as
in my example.
Still leaving the question open, why, when declaring
your second example as function and call it in the main
code, Perl will issue the "will not stay shared" message,
while running the code as-is, it does not, as in these
examples:
{ sub f {
my $r; my $r;
sub x { $r } sub x { $r }
} }
-- No message -- Variable "$r" will not stay shared...
And still leaving the question open, why this code _works_
as expected:
{
my $r = 1;
sub f { print $r }
f(); # print 1
$r++;
f(); # print 2
}
although, as mentioned in previous postings, in this case,
function f is evaluated (compiled) only once?
BTW: again, when writing this as function, Perl still will
issue the "will not stay shared" message, although here,
$r will stay shared!
Greetings, Ferry
--
Ing Ferry Bolhar
Magistrat der Stadt Wien - MA 14
A-1010 Wien
E-Mail: bol@xxxxxxxxxxxxxxxxx
.
- References:
- Interesting behaviour with lexical variable
- From: Ferry Bolhar
- Interesting behaviour with lexical variable
- Prev by Date: Re: Problem installing ExtUtils::Command from CPAN
- Next by Date: Re: opening things without the O_LARGEFILE flag
- Previous by thread: Re: Interesting behaviour with lexical variable
- Next by thread: Re: Printing and Formatting data from hash (or array)
- Index(es):
Relevant Pages
|