Thursday, April 22, 2010

BEGIN, INIT, CHECK, UNITCHECK, END : Five different code blocks

These are different types of code blocks available in Perl, which get executed during start and end of any Perl program. One can have more than one of these blocks in any Perl program, and will get executed in appropriate moment.

BEGIN: It gets executed in Compile time, as soon as possible, even before the rest of the file is parsed. There may be multiple BEGIN{} blocks and they will be executed in FIFO.

END : It is executed as late as possible, that is, after Perl has finished running the program and just before the interpreter is being exited, even if it is exiting as a result of a die() function. There may be multiple END{} Blocks, within a file. They will be executed in LIFO(reverse) order. END blocks are not executed when you run Perl with -c switch i.e. It's not called in compile time.

UNITCHECK: It's called after the unit which defined them has been compiled. The main program file and module it loads are compilation units.

CHECK: These are run just after initial compile phase ends and before the run time begins in LIFO order. These are used by Perl compile suite to save the compiled state of the program.

INIT : These are run just before Perl run time begins execution in FIFO Order.

INIT, CHECK, UNITCHECK, blocks are used to catch the transition between compilation phase and execution phase of main program.
##########################################################
# One example program for Perl mod
print "8. Ordinary code runs at runtime.\n";

 END { print "12. Read perlmod for the rest of the story.\n" }
 INIT { print " 6. INIT blocks run FIFO just before runtime.\n" }
 UNITCHECK { print " 4. And therefore before any CHECK blocks.\n" }

 print "9. It runs in order, of course.\n";

 BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
 CHECK { print " 5. CHECK blocks run LIFO after all compilation.\n" }
 BEGIN { print " 2. So this line comes out second.\n" }
 INIT { print " 7. Run this again, using Perl's -c switch.\n" }
 END { print "11. END blocks run LIFO at quitting time.\n" }
 UNITCHECK { print " 3. UNITCHECK blocks run LIFO after each file is compiled.\n" }

 print "10. It merely _looks_ like it should be confusing.\n";

No comments:

Post a Comment