in reply to Setting lexicals in a BEGIN block.

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.

Replies are listed 'Best First'.
Re: Re: Setting lexicals in a BEGIN block.
by Anonymous Monk on Jun 21, 2002 at 07:58 UTC
    The vars pragma is not block-scoped, but file scoped

    In fact, the documentation is a little off on that one. The vars pragma is neither block nor file scoped, it is package scoped.

      It's better to say that it isn't scoped at all. All the vars pragma does is, after some checking of arguments, is using the fully qualified variable in a dummy statement. There is no scoping involved.

      Abigail

        By package scoped I mean that unqualified use of a variable declared with use vars qw($foo) follows package boundaries: 1) unqualified use of $foo is not allowed inside another package (even in the same file as the declaration), and 2) unqualified use of $foo is allowed anywhere within the same package (even in different files from the declaration).