This question requires an understanding of compiler phase, vs the BEGIN
block. From Programming Perl: 3rd Edition - Page 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 likeeval STRING
.
Let's take very a simple example
sub complex_sub {
die 'code run';
}
sleep 5;
print 'good';
use constant FOO => complex_sub();
if the above is run as-is, then complex_sub
from the users perspective is run in the compiler phase. However, with slight modifications I can have..
# 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;
}
In the above code complex_sub
is run in the execution phase. Is there anyway to differentiate these two cases from the perspective of complex_sub
to enable the top syntax, but to prohibit the bottom syntax.
Use the ${^GLOBAL_PHASE}
variable. It contains "START" in the first case, but "RUN" in the second one.
# RUN
perl -wE'say ${^GLOBAL_PHASE}'
# START
perl -wE'BEGIN {say ${^GLOBAL_PHASE}}'
# RUN
perl -wE'eval q{BEGIN {say ${^GLOBAL_PHASE}}}'
See perlvar for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With