Perl begin and end blocks
February 09, 2011 15:35:41 Last update: February 09, 2011 15:36:08
Perl
A
An
A test:
BEGIN and END blocks are executed at the beginning and at the end of a running Perl program. By the Perl doc:
- A
BEGINcode 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. You may have multipleBEGINblocks within a file (or eval'ed string); they will execute in order of definition. Because a BEGIN code block executes immediately, it can pull in definitions of subroutines and such from other files in time to be visible to the rest of the compile and run time. Once aBEGINhas run, it is immediately undefined and any code it used is returned to Perl's memory pool. - An
ENDcode block 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. (But not if it's morphing into another program via exec, or being blown out of the water by a signal--you have to trap that yourself (if you can).) You may have multipleENDblocks within a file -- they will execute in reverse order of definition; that is: last in, first out (LIFO).ENDblocks are not executed when you run Perl with the-cswitch, or if compilation fails.
A
BEGIN block looks like this:
BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
An
END block looks like this:
END { print "14. END blocks run LIFO at quitting time.\n" }
A test:
END { print "END block is executed last even when it's defined first\n"; } goto END; BEGIN: { print "This is a block with a label named BEGIN\n"; } goto EXIT; END: { print "This is a block with a label named END\n"; } goto BEGIN; EXIT: print "Exiting!\n"; exit(0); BEGIN { print "BEGIN block could appear last but still executed first\n"; }
Easy email testing with http://www.ximailstop.com