Interesting behaviour with lexical variable
- From: "Ferry Bolhar" <bol@xxxxxxxxxxxxxxxxx>
- Date: Mon, 30 Oct 2006 17:37:43 +0100
Hi to all,
while playing with code like this:
use warnings;
while (my $input = <STDIN>){
my $num = abs $input;
print add();
sub add {
$num + $num;
}
}
I found out that once the loop get executed for the second
time, the variable $sum gets "splitted", taking the new value
from $input in the loop, but leaving the old, previous value
in add().
I was wondered a litte bit because I couldn't found described
this behaviour anywhere in the docs.
If, however, the entire code is placed again in another function,
and this function is then called:
use warnings;
sub main {
... # See above, starting with "while..."
}
main();
I get this message:
Variable "$num" will not stay shared at x.pl line 11.
explaining what actually will happen here (although I can't
understand _why_ it does happen - it's the same lexical
variable within the same scope - so why will/can it not
longer stay shared?).
So just for curiosity this question: the same behaviour
occurs twice, but gets reported only once. Is this expected
or perhaps a (small) bug?
BTW: This is perl 5.8.8 (as well as 5.6.1).
Greetings, Ferry
--
Ing Ferry Bolhar
Magistrat der Stadt Wien - MA 14
A-1010 Wien
E-Mail: bol@xxxxxxxxxxxxxxxxx
.
- Follow-Ups:
- Re: Interesting behaviour with lexical variable
- From: jl_post@xxxxxxxxxxx
- Re: Interesting behaviour with lexical variable
- Prev by Date: Re: Windows services in PERL
- Next by Date: Re: Naive threading performance questions
- Previous by thread: Re: Windows services in PERL
- Next by thread: Re: Interesting behaviour with lexical variable
- Index(es):
Relevant Pages
|