I understand that the BEGIN is executed before the main program. The questions are:
- what is the main program when talking about an PGSI application - or better
- when will be executed the BEGIN block in an PGSI app?
- It is different for
plackuporStarmanand like? - What about the middlewares - when have multiple BEGIN blocks?
Example app.psgi:
use Modern::Perl;
use YAML;
use Plack::Builder;
use CGI::Emulate::PSGI;
our($cfg);
BEGIN {
$cfg = YAML::LoadFile("my.config");
}
#old really __BIG__ cgi application - what uses many BEGIN blocks too...
my $app1 = CGI::Emulate::PSGI->handler(sub {
use My::CgiApp1;
My::CgiApp1::executer->run();
});
my $app2 = sub { ... };
builder {
mount "/path1" => $app1;
mount "/" => $app2;
}
In what order will be executed the multiple BEGIN blocks what are defined in My::CgiApp1 and my app.pgsi?
From the above PSGI application's point of view what is the main difference using:
BEGIN {
$cfg = YAML::LoadFile("my.config");
}
or an simple
$cfg = YAML::LoadFile("my.config");
BEGINblocks are executed during the compilation phase immediately the end of the block is seen by the compiler.That means each
BEGINblock is executed only once, before the main run starts, and the blocks are executed in the order the compiler sees them.Remember that a
usestatement is essentiallyrequirein a hiddenBEGINblock, so in your case the compiler will process the main program, executing theYAML::LoadFileas soon as the closing brace of itsBEGINblock is seen. Then it will continue compiling the program untiluse My::CgiApp1, when it will suspend processing the main program and start to compileMy/CgiApp1.pm.Perl will now execute any
BEGINblocks it finds in this file as they are encountered, and similarly suspend processing in the case of any furtherusestatements.As soon as the module specified in any
usestatement has finished compilation, processing will continue in the original file with next line of code.All of this happens before
My::CgiApp1::executer->runis executed, which is an ordinary statement and so is performed at run time.