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; ... }
perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

In reply to Re: Variable scope by shmem
in thread Variable scope by Alphaphi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.