Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: BEGIN vs initialization

by ikegami (Pope)
on Nov 29, 2009 at 00:00 UTC ( #809955=note: print w/ replies, xml ) Need Help??


in reply to BEGIN vs initialization

Your questions don't make sense because there's no initialisation in Perl in the sense that you're picturing. Here's what you are missing:

  • "=" doesn't denote an initialiser in Perl. It's always just a normal assignment.
  • BEGIN blocks are executed as soon as they are compiled.
  • use Module; is the same as BEGIN { require Module; import Module; }.
  • Using require to load a file simply runs it as any other script (if it's not already loaded). It is both compiled and executed.

Taking a simplified version of your code

#main.pl use Gbl; BEGIN{ $Gbl::runContext = $Gbl::runSMTP; } ...
# GBL.pm package Gbl; our $runSMTP = 2 1;

Let's apply what I've said above to determine the order in which everything is executed
main.pl
  1. Compile the code.
    1. use Gbl; is compiled.
    2. use Glb; is executed. (BEGIN blocks are executed as soon as they are compiled.)
      1. require Gbl; is executed.
        Gbl.pm
        1. Compile the code.
          1. package Gbl; is compiled.
          2. our $runSMTP = 2; is compiled.
          3. 1; is compiled.
        2. Execute the code.
          1. our $runSMTP = 2; is executed. (This is where 2 is assigned to $runSMTP.)
          2. 1; is executed.
      2. import Gbl; is executed.
    3. BEGIN { ... } is compiled.
      1. $Gbl::runContext = $Gbl::runSMTP; is compiled.
    4. BEGIN { ... } is executed. (BEGIN blocks are executed as soon as they are compiled.)
      1. $Gbl::runContext = $Gbl::runSMTP; is executed. (This is where 2 is assigned to $runContext.)
    5. The rest of the program ("...") is compiled.
  2. Execute the code.
    1. The rest of the program ("...") is executed.


Comment on Re: BEGIN vs initialization
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://809955]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2014-09-22 22:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (207 votes), past polls