Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop code from being run in the compiler phase?

Tags:

constants

perl

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 like eval 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.

like image 310
NO WAR WITH RUSSIA Avatar asked Jan 15 '20 14:01

NO WAR WITH RUSSIA


Video Answer


1 Answers

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.

like image 164
choroba Avatar answered Sep 19 '22 06:09

choroba