The code under discussion is effectively this:

our $initialized = 0; BEGIN { $initialized = 1; } more stuff

The significant information is that our $variable = value has both a compile-time and a runtime effect.

When Perl parses the first line, it sees the variable declaration - the compile-time effect - and therefore knows how to interpret other references to this variable in the rest of the lexical scope (file scope in this case). It also sees the assignment, and compiles that to be executed at runtime (the runtime effect).

When it parses the second line it sees the BEGIN block, so as soon as it has reached the end of the block it suspends parsing to execute the block. At this point the runtime assignment $initialized = 0 has not yet happened.

It then resumes parsing the file, and once the entire file has been compiled it then executes the top-level code. This is the point at which the variable gets set to zero.

Hugo


In reply to Re^3: What can we assume in a BEGIN block ? by hv
in thread What can we assume in a BEGIN block ? by leriksen

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.