Search code examples
perlruntimecompile-time

Compile time and run time in Perl


I am reading this document to understand the life cycle of a Perl program.

When do run time and when do compile time events occur while running a Perl script on a command line like this:

perl my_script.pl

Solution

  • perl script.pl will compile script.pl then execute script.pl. Similarly, require Module; will compile Module.pm then execute Module.pm.

    If the compiler encounters a BEGIN block, it will execute the block as soon as the block is compiled. Keep in mind that use is a BEGIN block consisting of a require and possibly a import.

    For example,

    # script.pl
    use Foo;
    my $foo = Foo->new();
    $foo->do();
    

    Does:

    1. Compile script.pl
      1. Compile use Foo;
      2. Execute require Foo;
        1. Compile Foo.pm
          1. ...
        2. Execute Foo.pm
          1. ...
      3. Execute import Foo;
      4. Compile my $foo = Foo->new();
      5. Compile $foo->do();
    2. Execute script.pl
      1. Execute my $foo = Foo->new();
      2. Execute $foo->do();