据我了解 Perl 代码中的这些特殊功能,BEGIN 和 CHECK block 在编译阶段运行,而 INIT 和 END block 在实际执行阶段运行。
我可以理解在实际的 Perl 代码(Perl 库)中使用这些 block ,但是在模块中使用它们呢?那可能吗?
从我们使用 use <Module-name>
开始该模块已编译,因此实际上 BEGIN 和 CHECK block 运行。但是 INIT 和 END block 将如何运行,因为我认为模块代码不是真正意义上的运行。我们只使用模块内部的某些功能。
最佳答案
短 通过 use
加载的包中的特殊代码块处理和运行(或计划运行)如遇到,以与 main::
中相同的方式和顺序, 自 use
本身是一个 BEGIN
堵塞。
可以找到这方面的优秀文档 in perlmod .从这个部分
A BEGIN code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.
由于
use
语句是 BEGIN
他们一遇到就会运行的 block 。来自 useIt is exactly equivalent to
BEGIN { require Module; Module->import( LIST ); }
所以
BEGIN
包中的 block 在遇到时与其他 block 一起运行。 END
包中的 block 以及其他特殊 block 也以相同的顺序编译。至于(最终)执行的顺序An
END
code block is executed as late as possible ...
和
You may have multiple END blocks within a file--they will execute in reverse order of definition; that is: last in, first out (LIFO)
INIT
的编译执行顺序和 CHECK
block 效仿。下面是一些代码来演示包中使用的这些特殊代码块。
文件 包 block .pm
package PackageBlocks;
use warnings;
BEGIN { print "BEGIN block in the package\n" }
INIT { print "INIT block in the package\n" }
END { print "END block in the package\n" }
1;
主要脚本
use warnings;
BEGIN { print "BEGIN in main script.\n" }
print "Running in the main.\n";
INIT { print "INIT in main script.\n" }
use PackageBlocks;
END { print "END in main script.\n" }
BEGIN { print "BEGIN in main script, after package is loaded.\n" }
print "After use PackageBlocks.\n";
输出
在主脚本中开始。
包中的 BEGIN block
在加载包后,在主脚本中开始。
主脚本中的初始化。
包中的 INIT block
跑为主。
使用 PackageBlocks 之后。
在主脚本中结束。
包中的 END block
BEGIN
与 main::
中的 block 相比,包中的 block 按出现顺序运行, 之前 INIT
. END
block 运行结束,并且包中的那个在
main::
中的那个之后运行, 因为 use
在这个例子中出现在它之前。
关于perl - Perl 中的 BEGIN、CHECK、INIT 和 END block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37723430/