How can I compile a perl script inside a running perl session?

I have a Perl script that accepts user input and creates another script that will be launched later. I am currently reviewing and writing tests for these scripts, and one of the tests that I would like to run checks if the generated script is generated (e.g perl -c <script>..) Is there a way that I can get Perl to execute the compilation of the generated script without having to run another Perl process? I tried to find the answers, but the searches simply include information about compiling Perl scripts in executable programs.

+5
source share
4 answers

To execute dynamically generated code, use the function eval:

my $script = join /\n/, <main::DATA>;
eval($script);   # 3

__DATA__

my $a = 1;
my $b = 2;
print $a+$b, "\n";

However, if you just want to compile or check the syntax, you cannot do this within a single Perl session.

The function syntax_okfrom the Test :: Strict library will check the syntax by running perl -cperl with an external interpreter, so I’ll assume that there is no internal path.

Only work that can work for you will:

my $script = join /\n/, <main::DATA>; 
eval('return;' . $script); 
warn $@ if $@;   # syntax error at (eval 1) line 3, near "1
                 # my "

__DATA__ 

my $a = 1
my $b = 2; 
print $a+$b, "\n";

In this case, you can check for compilation errors with $@, however, since the first line of code return;, it will not execute.


Note. Thanks to mob for helpful chats and code fixes.

+3
source

a script . . . .. , -, . , script , .

+6

Would this work for you?

open(FILE,"perl -c generated_script.pl 2>&1 |");
@output=<FILE>;
if(join('',@output)=~/syntax OK/)
{
   printf("No Problem\n");
}
close(FILE);
+1
source

See Test::Compileespecially pl_file_ok().

+1
source

All Articles