Subhayan Bhattacharya Subhayan Bhattacharya - 1 year ago 138
Perl Question

BEGIN,CHECK,INIT& END blocks in Perl

As per my understanding of these special functions inside Perl code , BEGIN and CHECK blocks run during compilation phase while INIT and END blocks run during actual code running phase .

I can understand using these blocks inside actual Perl code (Perl libraries) but what about using them inside modules ? Is that possible .

Since when we use "use " the module is compiled, so in effect BEGIN and CHECK blocks run . But how will the INIT and END blocks run since module code i don't think is run in the true sense. We only use certain functions from inside the modules.

Answer Source

An excellent documentation page on this can be found in perlmod.

Here is some code to demonstrate these special code blocks used in a package.


package pack_BEGIN;
use warnings;

BEGIN {  print "In BEGIN in the package\n" }
INIT  { print "In INIT in the package\n" }
END  { print "In END block in the package\n" }

The main script

use warnings;

BEGIN { print "BEGIN in main script\n" }

print "Running in the main\n";

INIT { print "INIT in main script.\n" }

use pack_BEGIN;

END { print "END in main script\n" }
BEGIN { print "BEGIN in main script, after package is loaded\n" }

print "After use pack_BEGIN\n";


BEGIN in main script
In BEGIN in the package
BEGIN in main script, after package is loaded
INIT in main script.
In INIT in the package
Running in the main
After use pack_BEGIN
END in main script
In END block in the package

The BEGIN block in the package runs before INIT, and you can use it similarly to how it is used in main::. Note that, per the above page in perlmod

A BEGIN code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.

The END block in the package runs after the END in main::. An END code block is executed as late as possible, and per the same page

You may have multiple END blocks within a file--they will execute in reverse order of definition; that is: last in, first out (LIFO)

The order of execution of INIT blocks is easily understood, see code and output.

So these code blocks in the package seem to follow the behavior of those in main::.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download