Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I get this:use strict sub foo { bar(1); bar(2); bar(4); } sub bar { print $_[0] . "bar----------\n"; my $x = 0 if 1 == 2; defined $x ? print $x : print '$x und'; print "\n"; my $y; $y = 0 if 1 == 2; defined $y ? print $y : print '$y und'; print "\n"; $x = $_[0]; $y = $_[0]; bar(3) if $_[0] == 2; } foo();
I'm not very familiar with perl but this result doesn't really mesh with my idea of possible scoping rules for "my". My understanding of what's going on is that when the declaration of $x fails, $x retains the value from the previous call to bar(). This implies a 'static local'-like scope. However, this breaks down when the recursive call does not produce a similar result. If anyone can clear my understanding up, I would appreciate it. As shown with $y, it's easy to work around this issue, but I'd rather have a clearer understanding of the scoping.1bar---------- $x und $y und 2bar---------- 1 $y und 3bar---------- $x und $y und 4bar---------- 2 $y und
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Confusion over scope of "my" vars
by ikegami (Patriarch) on Nov 26, 2008 at 17:53 UTC | |
|
Re: Confusion over scope of "my" vars
by almut (Canon) on Nov 26, 2008 at 18:01 UTC | |
|
Re: Confusion over scope of "my" vars
by JavaFan (Canon) on Nov 26, 2008 at 18:02 UTC | |
|
Re: Confusion over scope of "my" vars
by Anonymous Monk on Nov 26, 2008 at 18:16 UTC | |
by LanX (Saint) on Nov 26, 2008 at 18:20 UTC | |
by JavaFan (Canon) on Nov 26, 2008 at 18:24 UTC | |
by LanX (Saint) on Nov 26, 2008 at 18:31 UTC | |
by ikegami (Patriarch) on Nov 26, 2008 at 21:00 UTC | |
| |
|
Re: Confusion over scope of "my" vars
by mikelieman (Friar) on Nov 26, 2008 at 17:56 UTC |