Search code examples
perlruntimecompile-time

What is the meaning of 'at compile-time' in Perl scripting?


I have read this about Perl:

Perl is an interpreted language and doesn't compile.

And I also see talk of at compile-time and at run-time.

Especially when I look for use of use and require, it shows a difference:

use normally loads the module at compile time whereas require does at run time.

Does Perl really compile the script? What is the meaning of 'at compile-time' in Perl scripting?


Solution

  • Perl does compile, prior to running. Usually that's done immediately before. Running perl -c will do a fairly basic code validity check, and will highlight certain classes of errors (usually in my case, missing semi-colons).

    From perlrun:

    After locating your program, Perl compiles the entire program to an internal form. If there are any compilation errors, execution of the program is not attempted. (This is unlike the typical shell script, which might run part-way through before finding a syntax error.)

    That includes loading and checking any imported modules for the same tests. In most cases that's exactly what you want - these tests/errors are usually show stoppers, and so detecting before even starting to execute is a good thing.

    Especially when you use strict; and use warnings; your code is preprocessed for a wider range of errors. It is done at compile time, and it'll abort if anything it spotted.

    Again, this is usually desirable - tripping over glitches halfway through a program is usually more annoying to sort out, as you're potentially in an inconsistent state.

    However as you note - things like modules can be pretty big, and it can be useful as a result to load them 'on the fly'. Perl can redefine a bunch of things as you go - if you really want you can make/change subroutines within your code.

    Changes to subroutines and testing their validity can't ever be done at "compile time" because of what is known as the halting state problem. So you load at run time, but then have to build in some more exhaustive integrity checking.