Item 59: Initialize with BEGIN ; finish with END .Often you will need to initialize subroutines and/or packages before they are first used. Perl provides a mechanism, BEGIN blocks, that allows you to execute initialization code at program start-up. Perl also provides a complementary mechanism, END , that allows you to execute code just before program termination. BEGINA BEGIN block encloses code that is to be executed immediately after it is compiledbefore any following code is compiled. For example, you can use BEGIN to initialize a variable that a subroutine later will use: Use BEGIN blocks to enclose initialization code.
Because the contents of BEGIN blocks are compiled and executed before any "normal" code, it generally does not matter where a BEGIN block goes. In many cases, the best place to put a BEGIN block is inside the subroutine or other code that needs it: Place BEGIN blocks where they are most convenient .
BEGIN blocks can also be used in combination with my to create private static variables like those in C (see also Item 29): Use my and BEGIN blocks to create static variables.
You can even create shared static variables: Create shared static variables with my and BEGIN blocks.
Because code in a BEGIN block is compiled and executed immediately as it is encountered during the compile phase, code in a BEGIN block can alter compile-time semantics. In particular, a BEGIN block can create and define functions that work as list operatorsjust as though they had been declared in the program text (also see Item 10):
Because require (see Item 54) is basically a form of eval , we can use BEGIN blocks to "import" functions from files containing Perl source code: Combining BEGIN with require
In fact, this is the mechanism employed by Perl's use directive, and it is the basis for writing modules in Perl 5:
See Item 42 for more about Perl modules. ENDEND blocks enclose code that will be executed just as a Perl program terminates. END blocks are useful for cleaning upgetting rid of lockfiles, releasing semaphores, and so forth: Use END locks to enclose program clean-up code.
END blocks are executed during any "planned" terminationthe end of the script, exit , die , and so on. Multiple END blocks are executed in reverse of the order in which they were encountered during compilation. END blocks are not executed in other casesuncaught signals, Perl panics, before exec , et cetera. |