Beefy Boxes and Bandwidth Generously Provided by pair Networks Russ
go ahead... be a heretic
 
PerlMonks  

perlfunc:do

by gods
on Aug 24, 1999 at 22:42 UTC ( #236=perlfunc: print w/ replies, xml ) Need Help??

do

See the current Perl documentation for do.

Here is our local, out-dated (pre-5.6) version:


do - turn a BLOCK into a TERM



do BLOCK

do SUBROUTINE(LIST)

do EXPR



Not really a function. Returns the value of the last command in the sequence of commands indicated by BLOCK. When modified by a loop modifier, executes the BLOCK once before testing the loop condition. (On other statements the loop modifiers test the conditional first.)

A deprecated form of subroutine call. See the perlsub manpage.

Uses the value of EXPR as a filename and executes the contents of the file as a Perl script. Its primary use is to include subroutines from a Perl subroutine library.

    do 'stat.pl';

is just like

    scalar eval `cat stat.pl`;

except that it's more efficient and concise, keeps track of the current filename for error messages, and searches all the -I libraries if the file isn't in the current directory (see also the @INC array in Predefined Names). It is also different in how code evaluated with do FILENAME doesn't see lexicals in the enclosing scope like eval STRING does. It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop.

If do cannot read the file, it returns undef and sets $! to the error. If do can read the file but cannot 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.

Note that inclusion of library modules is better done with the use() and require() operators, which also do automatic error checking and raise an exception if there's a problem.

You might like to use do to read in a program configuration file. Manual error checking can be done this way:

    # read in config files: system first, then user 
    for $file ("/share/prog/defaults.rc",
               "$ENV{HOME}/.someprogrc") {
        unless ($return = do $file) {
            warn "couldn't parse $file: $@" if $@;
            warn "couldn't do $file: $!"    unless defined $return;
            warn "couldn't run $file"       unless $return;
        }
    }

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2014-04-18 10:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (466 votes), past polls