Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect compile phase in Perl

I'm working with a module that makes use of some prototypes to allow code blocks. For example:

sub SomeSub (&) { ... }

Since prototypes only work when parsed at compile time, I'd like to throw a warning or even a fatal if the module is not parsed at compile time. For example:

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

Is there a way to detect if something is being executed at compile or run time/phase in Perl?

like image 903
Francisco Zarabozo Avatar asked Jan 10 '23 20:01

Francisco Zarabozo


1 Answers

If you're running on Perl 5.14 or higher, you can use the special ${^GLOBAL_PHASE} variable which contains the current compiler state. Here's an example.

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();

Output:

all's good
not in compile-time!
like image 71
friedo Avatar answered Jan 12 '23 09:01

friedo