检测Perl中的编译阶段

时间:2014-09-08 19:28:56

标签: perl runtime compile-time

我正在使用一个模块,该模块使用一些原型来允许代码块。例如:

sub SomeSub (&) { ... }

由于原型只能在编译时解析,所以如果在编译时没有解析模块,我想发出警告甚至是致命的。例如:

require MyModule; # Prototypes in MyModule won't be parsed correctly

有没有办法检测在Perl中编译或运行时/阶段是否正在执行某些操作?

2 个答案:

答案 0 :(得分:4)

如果您在Perl 5.14或更高版本上运行,则可以使用包含当前编译器状态的特殊${^GLOBAL_PHASE}变量。这是一个例子。

use strict;
use warnings;

sub foo {
    if ( ${^GLOBAL_PHASE} eq 'START' ) {
        print "all's good\n";
    } else {
        print "not in compile-time!\n";
    }
}

BEGIN {
    foo();
};

foo();

输出:

all's good
not in compile-time!

答案 1 :(得分:4)

在5.14之前(或之前或之后),您可以:

package Foo;
BEGIN {
    use warnings 'FATAL' => 'all';
    eval 'INIT{} 1' or die "Module must be loaded during global compilation\n";
}

但是(和${^GLOBAL_PHASE})并没有完全检查你想知道什么,这是否正在编译或运行包含use / require语句的代码。

相关问题