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.
#== Context ============
our $runHTTP = 1;
our $runSMTP = 2;
our $runContext = $runHTTP; # HTTP ...variable assignment might be af
#our $runContext = 1; # HTTP ...variable assignment might be a
This is the main controlling file (which will 'use Gbl;"
use feature qw( :5.10 );
use File::Temp qw/ tempfile tempdir /;
use lib "/usr/local/mySystem";
# 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" ;
If the initialization executes immediately after parse, then
- $runHTTP is set to 1 durnig Gbl parse upon 'use' in main.pl
- $runSMTP is set to 2 durnig Gbl parse upon 'use' in main.pl
- $runContext = $runHTTP upon parse (==1)
- $Gbl::runContext = $Gbl::runSMTP (==2) upon BEGIN in main.pl
If it is at execute time
- code to set $runHTTP to 1 is prepared durnig Gbl parse upon 'use' in main.pl
- code to set $runSMTP to 2 is prepared durnig Gbl parse upon 'use' in main.pl
- code to set $runContext = $runHTTP is prepared upon parse
- $Gbl::runContext = $Gbl::runSMTP (== undef) upon BEGIN in main.pl
- 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.