gpt4 book ai didi

perl - 如何停止在编译器阶段运行代码?

转载 作者:行者123 更新时间:2023-12-04 13:36:01 24 4
gpt4 key购买 nike

这个问题需要了解编译器阶段,而不是BEGIN块。从Perl编程:第3版-第467页

It's also important to understand the distinction between compile phase and compile time, and between run phase and run time. A typical Perl program gets one compile phase, and then one run phase. A "phase" is a large-scale concept. But compile time and run time are small-scale concepts. A given compile phase does mostly compile-time stuff, but it also does some run-time stuff via BEGIN blocks. A given run phase does mostly run-time stuff, but it can do compile-time stuff through operators like eval STRING.



让我们举一个非常简单的例子
sub complex_sub {
die 'code run';
}
sleep 5;
print 'good';
use constant FOO => complex_sub();

如果以上命令按原样运行,那么从用户角度来看, complex_sub将在编译器阶段运行。但是,只要稍加修改,我就可以拥有..
# Bar.pm
package Bar {
use constant FOO => main::complex_sub();
}

# test.pl
package main {
sub complex_sub {
die 'code run';
}
sleep 5;
print 'good';
require Bar;
}

在上面的代码中, complex_sub在执行阶段运行。无论如何,从 complex_sub的角度来区分这两种情况以启用顶部语法,但禁止底部语法。

最佳答案

使用${^GLOBAL_PHASE}变量。在第一种情况下,它包含“START”,在第二种情况下,它包含“RUN”。

# RUN
perl -wE'say ${^GLOBAL_PHASE}'

# START
perl -wE'BEGIN {say ${^GLOBAL_PHASE}}'

# RUN
perl -wE'eval q{BEGIN {say ${^GLOBAL_PHASE}}}'

有关详细信息,请参见 perlvar

关于perl - 如何停止在编译器阶段运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59753701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com