To execute dynamically generated code, use the function eval:
my $script = join /\n/, <main::DATA>;
eval($script);
__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 $@;
__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.
Ωmega source
share