I always assume that subroutines will be put into a scope where they will be compiled and never run [ that is, the subroutine will probably be called, but the lines around the subroutine will never be run ].

If you don't use the BEGIN, then you have a race condition because the subroutine exists and can be called as soon as it is compiled but its "static variable" (will be declared but) won't be initialized until that line gets run, which could happen much later or not at all.

I first ran into this problem with some border cases of using modules. The one that I remember was having two modules that depend on each other. Perl actually manages to get this mostly right (doing better than I would have thought was even possible). But the effect is that if A.pm uses B.pm which uses A.pm, then either A::import() or B::import() will be called before the code for that module gets run. I recall finding another case that was less easy to justify ignoring, but I don't remember the specifics right now.

Another case is self-inflicted. I hate having to read "between" a huge list of subroutine declarations looking for the run-time statements so I force my top-level run-time code into sub main and enforce this discipline by ending my global declarations with:

exit( main( @ARGV ) );
(see (tye)Re: Stupid question for other self-inflicted discipline).

So I guess that boils down to "No, I don't have any glaring, screaming, obvious cases that make not doing this a really, really bad idea." (: It is a personal coding habit that has saved me time more than once. It avoids a race condition, which is usually a good thing.

        - tye (but my friends call me "Tye")

In reply to (tye)Re2: Very very small style question by tye
in thread Very very small style question by Dominus

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.