After a few Super Searches, I figured out a few ways to set a file-scoped variable within said BEGIN block, and I'm wondering which is the Best Way, or if it's just a matter of programmer preference.

It's more a programmer preference. I try to avoid setting lexicals in BEGIN blocks. If you do set a lexical, make sure it is declared before the BEGIN block, because otherwise, the variable will be lost forever (unless used in a closure like your get_obj).

I find this odd, since a "use vars" variable works, but "our" doesn't. Aren't the two the same thing?

The vars pragma is not block-scoped, but file scoped (this is documented, use the link). If you use "our" inside the block, you can use the variable unqualified (qualified is $Package::variable) in the block, but not outside of it. If you use "use vars" inside the block, you can use the variable everywhere in the file. You could move the "our" statement to some place before the block, or repeat the "our" elsewhere. The same variable will be used (a second "our $foo" does not create a new $foo), as it is a normal global.

- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.


In reply to Re: Setting lexicals in a BEGIN block. by Juerd
in thread Setting lexicals in a BEGIN block. by mephit

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.