do (file)

do FILEThe do
FILE form uses the value of FILE as
a filename and executes the contents of the file as a Perl script. Its
primary use is (or rather was) to include subroutines from a Perl
subroutine library, so that:
do "stat.pl";
is rather like:
scalar eval `cat stat.pl`; # `type stat.pl` on Windows
except that do is more
efficient, more concise, keeps track of the current filename for error
messages, searches the directories listed in the @INC array, and updates %INC if the file is found. (See Chapter 25.) It also differs in that code evaluated with
do FILE
cannot see lexicals in the enclosing scope, whereas code in eval FILE does.
It’s the same, however, in that it reparses the file every time you call
it—so you might not want to do this inside a loop unless the filename
itself changes at each loop iteration.
If do can’t read the file, it
returns undef and sets $! to the error. If do can read the file but can’t compile it, it
returns undef and sets an error
message in $@. If the file is
successfully compiled, do returns the
value of the last expression evaluated.
Inclusion of library modules (which have a mandatory .pm suffix) is better done with the use and require operators, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access