in reply to Re: Confusion about BEGIN block
in thread Confusion about BEGIN block

I think I'm starting to get the hang of this, thankyou.

I guess my greatest confusion was where and when symbol names needed to be declared. Mmmm.

I think I understand that

1. our $var is lexically scoped, and is just an alias for $__PACKAGE::var

2. because our $var is lexically scoped, when it is in a BEGIN block, it does not mean that the alias (i.e. $var) is available outside of the BEGIN block.

3. however, if the alias is defined outside the BEGIN block, it will be available for use within the BEGIN block because of the lexical scope if and only if it is declared before the BEGIN block is written

EXAMPLE #1 works, #2 does not

#!/usr/bin/perl use strict; our %aa; our $bb; our @cc; print keys %aa,", $bb, @cc\n"; BEGIN {%aa=(1,11); $bb=22; @cc=(3,33); }
#!/usr/bin/perl use strict; BEGIN {%aa=(1,11); $bb=22; @cc=(3,33); } our %aa; our $bb; our @cc; print keys %aa,", $bb, @cc\n";
4. all code within the BEGIN block is executed first, regardless of it's location within the file

5. egads! no wonder I'm confused

Replies are listed 'Best First'.
Re^3: Confusion about BEGIN block
by revdiablo (Prior) on Oct 15, 2004 at 16:41 UTC
    egads! no wonder I'm confused

    It seems you are overthinking this a great deal. The reason strict complains is simple -- it scans the code before anything is executed, and looks for proper scoping. If there is a variable used before it is scoped, strict complains. End of story. Strict does not unravel BEGIN blocks and figure out what will be executed when, it simply looks at the "physical" location of things in the code.