Re: Interesting behaviour with lexical variable



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


.



Relevant Pages

  • Re: good practice
    ... Is there a good practice recommendation for the chars to use as delimiters ... as your default choice because qw/foo bar baz/ is becoming <foo bar ... Hope I will survive until Perl 6... ...
    (perl.beginners)
  • Re: equivalent of perl "next" command
    ... in perl the "next" command skips the remainder of the current loop iteration ...
    (microsoft.public.scripting.vbscript)
  • equivalent of perl "next" command
    ... in perl the "next" command skips the remainder of the current loop iteration ... What is the VBscript equivalent of this? ...
    (microsoft.public.scripting.vbscript)