简体   繁体   中英

Perl's BEGIN blocks in app.psgi

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 or Starman 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 essentially require in a hidden BEGIN block, so in your case the compiler will process the main program, executing the YAML::LoadFile as soon as the closing brace of its BEGIN block is seen. Then it will continue compiling the program until use My::CgiApp1 , when it will suspend processing the main program and start to compile My/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 further use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM