Perl begin and end blocks 

Joined:
04/09/2007
Posts:
727

February 09, 2011 15:35:41    Last update: February 09, 2011 15:36:08
Perl BEGIN and END blocks are executed at the beginning and at the end of a running Perl program. By the Perl doc:
  • 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. You may have multiple BEGIN blocks 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 a BEGIN has run, it is immediately undefined and any code it used is returned to Perl's memory pool.
  • An END code 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 multiple END blocks within a file -- they will execute in reverse order of definition; that is: last in, first out (LIFO). END blocks are not executed when you run Perl with the -c switch, 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";
}
Share |
| Comment  | Tags
 
Easy email testing with http://www.ximailstop.com