in reply to loading modules using 'use'

There's not a single compile-time. When one says "at compile-time", one means "when the containing unit (statement, block, file) is being compiled". Same goes for run time.

use A;
is basically
BEGIN { require A; A->import(); }

use statements and BEGIN blocks are executed as soon are they are compiled, so the following happens

  1. use A; is compiled.
  2. use A; is executed. (BEGIN blocks are executed as soon as they are compiled.)
    1. require A; is executed.
      1. If A hasn't previously been loaded,
        1. A is loaded and compiled.
          1. ...
          2. require Exporter; is compiled.
          3. @ISA = qw(Exporter); is compiled.
          4. @EXPORT = qw( abc ); is compiled.
          5. ...
        2. A is executed.
          1. ...
          2. require Exporter; is executed.
            1. If Exporter hasn't previously been loaded,
              1. Exporter is loaded and compiled.
                1. ...
                2. sub import { ... } is compiled.
                3. ...
              2. Exporter is executed.
                1. ...
          3. @ISA = qw(Exporter); is executed.
          4. @EXPORT = qw( abc ); is executed.
          5. ...
    2. A->import(); is executed.

As you can see, Exporter is loaded and its import method is compiled before your module's import is called without having to make any modifications.

(I usually use "ModA" instead of "A" because "B" is the name of an existing module.)

Replies are listed 'Best First'.
Re^2: loading modules using 'use'
by angshuman (Novice) on Jul 12, 2010 at 11:57 UTC
    Hi Monk,

    Thank you so very much for the step-by-step explanation,

    OK, in 2.1.1.1 you say A is loaded and compiled. So, what essentially is the difference between
    A.pm ~~~~~~~~~~ package A; require Exporter; @ISA = (Exporter); @EXPORT = qw(abc); AND A.pm ~~~~~~~~~~ package A; BEGIN{ require Exporter; @ISA = (Exporter); @EXPORT = qw(abc); }
    as irrespective of wheather BEGIN is there A is loaded and compiled, when 'use A' is encountered. But the BEGIN blocks provides a significant improvement in case of circular dependency/inheritance issues. How does the BEGIN block create such a difference then.

      If that's the entire file, there's essentially no difference between those two snippets.

      The BEGIN will affect the order in which those statements will be executed in relation to other statements in the file.

        That was just a sample module... Lets assume its got plenty of subroutines written in it, which are also included in the @EXPORT list. Then ???