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:

use File::Slurp;
use strict;
use warnings;

my $command = read_file('print.txt');
eval $command;

and here is the same code re-written using do:

use strict;
use warnings;

do 'print.txt';

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.

The official Perl documentation, Perldoc has more information on both do and eval.


This article was originally posted on PerlTricks.com.

Tags

David Farrell

David is the editor of Perl.com. An organizer of the New York Perl Meetup, he works for ZipRecruiter as a software developer.

Browse their articles

Feedback

Something wrong with this article? Help us out by opening an issue or pull request on GitHub