in reply to Variable scope
This is related to the hack used to implement state variables in subroutines, before state variables have been implemented in perl 5.10.0, which emits a warning on recent perls. It allocates the lexical variable on the subroutine's pad (or better: the pad of the current scope), but prevents it from being cleared:
#file state.pl sub foo { my $bar if 0; $bar++; print "foo called $bar times\n"; } foo for 'a'..'f'; __END__ Deprecated use of my() in false conditional at state.pl line 2. foo called 1 times foo called 2 times foo called 3 times foo called 4 times foo called 5 times foo called 6 times
This works also for lexical arrays.
However, if the conditional is declared beforehand as a variable, there is no such warning, since that warning happens at compile time, but the conditional is resolved at runtime:
# file state.pl my $cond; sub foo { my @bar if $cond; push @bar, @_; print "array \@bar = (@bar)\n"; } foo $_ for 'a'..'f'; $cond = 1; foo $_ for 1..6; __END__ array @bar = (a) array @bar = (a b) array @bar = (a b c) array @bar = (a b c d) array @bar = (a b c d e) array @bar = (a b c d e f) array @bar = (a b c d e f 1) array @bar = (2) array @bar = (3) array @bar = (4) array @bar = (5) array @bar = (6)
Huh? We have array @bar = (a b c d e f 1) here? Well, my variables are cleared at the end of their scope, so setting $cond = 1 doesn't clear the (state) array immediately.
If you don't have a sophisticated use (read: obfuscated use) for altering the behavior of my variables, you should use:
use feature qw(state); # also use 5.10.0; sub foo { state @bar; ... }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Variable scope
by choroba (Cardinal) on Apr 05, 2018 at 12:12 UTC | |
by shmem (Chancellor) on Apr 05, 2018 at 12:28 UTC | |
by Anonymous Monk on Apr 06, 2018 at 09:19 UTC | |
by Anonymous Monk on Apr 06, 2018 at 09:36 UTC | |
by choroba (Cardinal) on Apr 06, 2018 at 09:42 UTC | |
by Anonymous Monk on Apr 06, 2018 at 10:33 UTC | |
by choroba (Cardinal) on Apr 06, 2018 at 10:56 UTC | |
by Anonymous Monk on May 15, 2018 at 17:11 UTC | |
by choroba (Cardinal) on May 15, 2018 at 17:51 UTC |