Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

my, our, BEGIN

I hate scoping!



11:57 am on Sep 11, 2008 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member

ok, this is something that has always confused me. I have this:

[perl]my $foo = 13;
our $bar = 7;


ok, inside the BEGIN block it won't recognise $foo. This I get. However the thing that's annoying me, it will see $bar, but it won't yet have been assigned it's value of 7?

Is there a way to do this without sticking the definition inside the BEGIN block?


5:54 pm on Sep 11, 2008 (gmt 0)

5+ Year Member

The begin block runs as soon as possible, so the variables will not yet be available to the begin block. As far as I know, you will have to put them in the begin block. Its not a scoping issue really, its a compile time versus runtime issue.


7:46 am on Sep 13, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Maybe use (2) BEGIN blocks, one calls a "config vars" routine to scope and assigns the globals, second one pulls in the rest of the code ?

Maybe the answer is in here:

# begincheck
print "10. Ordinary code runs at runtime.\n";
END { print "16. So this is the end of the tale.\n" }
INIT { print " 7. INIT blocks run FIFO just before runtime.\n" }
UNITCHECK { print " 4. And therefore before any CHECK blocks.\n" }
CHECK { print " 6. So this is the sixth line.\n" }
print "11. It runs in order, of course.\n";
BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
END { print "15. Read perlmod for the rest of the story.\n" }
CHECK { print " 5. CHECK blocks run LIFO after all compilation.\n" }
INIT { print " 8. Run this again, using Perl's -c switch.\n" }
print "12. This is anti-obfuscated code.\n";
END { print "14. END blocks run LIFO at quitting time.\n" }
BEGIN { print " 2. So this line comes out second.\n" }
UNITCHECK { print " 3. UNITCHECK blocks run LIFO after each file is compiled.\n" }
INIT { print " 9. You'll see the difference right away.\n" }
print "13. It merely _looks_ like it should be confusing.\n";



4:23 pm on Sep 14, 2008 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member

Hmm, I have seen that extract before, but it's got me thinking, I'm using BEGIN, to run pre-runtime code. It basically does things like connecting to the DB, checking user session ID's, etc....

Looks like maybe I should change this to an INIT block, by that time compilation should be complete.

I'll give it a go and report back.


Featured Threads

Hot Threads This Week

Hot Threads This Month