http://qs1969.pair.com?node_id=809940

Wiggins has asked for the wisdom of the Perl Monks concerning the following question:

I want to use a BEGIN block to set a global context variable that other modules will use to adjust their control flow. But I remember the C++ "static initialization" pattern, which ran code before 'main' was called.

The question is
-When are initializations done?
-Are initialization code waiting to execute when the block is first entered?
-Are File globals initialized at parse or execute time?
-Is there any difference when initializing from a constant? a variable? a variable that is initialized from a constant? a function call?

When I began this 2 years ago, I could find no good documentation on the pragma "vars" other than "it pre-allocates global variables". That really says nothing about scope, mechanics, accessibility,... But I did get 'our' to work, and I like the explicit "Gbl::" prefix as self documentation.

This is the module of global values.

#GBL.pm package Gbl; #== Context ============ our $runHTTP = 1; our $runSMTP = 2; our $runContext = $runHTTP; # HTTP ...variable assignment might be af +ter BEGIN #our $runContext = 1; # HTTP ...variable assignment might be a +fter BEGIN # ... 1

This is the main controlling file (which will 'use Gbl;"

#main.pl use feature qw( :5.10 ); use strict; use warnings; use File::Temp qw/ tempfile tempdir /; use Email::MIME; use lib "/usr/local/mySystem"; use Gbl; BEGIN{ # Set some Globals for this environment $Gbl::runContext = $Gbl::runSMTP; #$Gbl::runContext = 2; $Gbl::pi_LogPath = "/tmp/primarylog.log" ; # log $Gbl::ds_LogPath = "/tmp/datalog.log" ; } use parseHTMP; use parseSMTP; #...

If the initialization executes immediately after parse, then

  1. $runHTTP is set to 1 durnig Gbl parse upon 'use' in main.pl
  2. $runSMTP is set to 2 durnig Gbl parse upon 'use' in main.pl
  3. $runContext = $runHTTP upon parse (==1)
  4. $Gbl::runContext = $Gbl::runSMTP (==2) upon BEGIN in main.pl
If it is at execute time
  1. code to set $runHTTP to 1 is prepared durnig Gbl parse upon 'use' in main.pl
  2. code to set $runSMTP to 2 is prepared durnig Gbl parse upon 'use' in main.pl
  3. code to set $runContext = $runHTTP is prepared upon parse
  4. $Gbl::runContext = $Gbl::runSMTP (== undef) upon BEGIN in main.pl
  5. Execution finally passed through Gbl, causing initialization code to execute.
    $Gbl::runContext = $Gbl::runHTTP

The initializers had not yet run in Gbl to define the variables at the point when main.pl's BEGIN block runs and accesses them?

It is always better to have seen your target for yourself, rather than depend upon someone else's description.