Use do to execute Perl code stored in files
Following our recent article on how to execute Perl code stored in a file using eval, Perl programmer mithaldu pointed out that the Perl built-in function do provides similar functionality.
This is a the text file ‘print.txt’:
print "it works! \n";
Here is the original solution using eval:
my $command = read_file('print.txt');
and here is the same code re-written using do:
Using do requires fewer lines of code then the eval solution and there is no need to open a filehandle or use a module to slurp the file (such as File::Slurp). The do function also updates @INC and %INC, so it can be used to load modules which are then used later in the program (eval does not do this).
One scenario where the eval approach would be needed instead of do would be if the text file contained non-Perl code that required parsing before the file is ready to be executed.
Using do does not replace the inherent risks associated with executing code stored in a separate file - this is a cool trick, not a recommended solution.
This article was originally posted on PerlTricks.com.
Something wrong with this article? Help us out by opening an issue or pull request on GitHub