The Perl "interpreter" "compiles" your Perl script before "running" it. This happens in a number of phases with stuff in BEGIN blocks being processed first, INIT block code is processed following compilation, then the main code is executed then, at exit time, the stuff in END blocks. require statements are processed at run time, but use statements are processed before any other main code statements.
Note that the location of a use statement doesn't alter when it is processed, only their order in the file affects the order that use statements are processed. In particular, you can not prevent a use statement from being processed by putting it inside an if, it is processed regardless.
I'm not completely happy with most documentation I see on "compile time" and "run time". They mostly encourage or at least don't discourage the impression that there is one time called "compile time" when your script is compiled and then there is one "run time".
In reality, each statement has its own "compile time" and any number of "run time"s.
I find it clearer and more accurate to think about more detailed steps that perl goes through, in order.
So, if I use require in my main script, then there can be whole files of Perl code that don't get compiled until after my main script has finished being compiled and has started running (and the require statement might not even get run).
Conversely, if I use that same require statement inside of a module that my main script uses, then those files will be compiled and their non-subroutine statements run before most of my main script is even compiled.
Update: s/of/off/. Thanks, gam3.
- tye
The complete story is more complicated, since Perl can also compile code on the fly even after the run phase has started (and can run code before the compile phase has completed). This is truly powerful, but difficult to wrap your head around.
But this is an aside. The problem in Perl is that certain operations can only be parsed completely in the run-time context.
Consider the following, for which C has no analog (buffer overflows notwithstanding).
my $str = $ARGV[0];
eval("use $str;");
Now, some theorists will complain bitterly that this must slow your code down, but this is usually the least of your problems. (See Optimising Perl.. for example)Thog.
perlmonks.org content © perlmonks.org and anilpal, gam3, GrandFather, kscaldef, thoglette, tye
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03