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
plackup
orStarman
and 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");
BEGIN
blocks are executed during the compilation phase immediately the end of the block is seen by the compiler.That means each
BEGIN
block is executed only once, before the main run starts, and the blocks are executed in the order the compiler sees them.Remember that a
use
statement is essentiallyrequire
in a hiddenBEGIN
block, so in your case the compiler will process the main program, executing theYAML::LoadFile
as soon as the closing brace of itsBEGIN
block 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
BEGIN
blocks it finds in this file as they are encountered, and similarly suspend processing in the case of any furtheruse
statements.As soon as the module specified in any
use
statement has finished compilation, processing will continue in the original file with next line of code.All of this happens before
My::CgiApp1::executer->run
is executed, which is an ordinary statement and so is performed at run time.