The closest thing I can find in the documentation is in perlsub:

A "my" has both a compile-time and a run-time effect. At compile time, the compiler takes notice of it. The principal usefulness of this is to quiet "use strict 'vars'", but it is also essential for generation of closures as detailed in perlref. Actual initialization is delayed until run time, though, so it gets executed at the appropriate time, such as each time through a loop, for example.

The section doesn't make it entirely obvious what's going on, and there are certainly no examples, but it is the explanation for why you're seeing what you are.

The canonical example is use as a static variable: sub foo { my $foo if 0; $foo++ }. perl sees the declaration at compile-time, so space is allocated for it, and it passes strict. But at run-time the variable is never initialized (my $foo; being equivalent to my $foo = undef;), so the value is left as it was.

This misfeature has been discussed several times on the perl5-porters mailing list. The last time I saw it there was resistance to documenting it in any form lest it be read as an official sanction for the syntax. It is, after all, a method of declaring a static variable, which can be useful.

In case anyone is curious, the proper way to declare a static is to use a closure:

{ my $foo; sub foo { $foo++ } } ... foo(); foo(); ...

In reply to Re: Conditional initialisation by Somni
in thread Conditional initialisation by Akhasha

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.