Package Initialization and Destruction
There are times when you want to do some initialization before any other code is executed. Perl goes further: it gives you a chance to execute code while it is still in the compilation stage.
Normally, while parsing a file, Perl
compiles the entire code, and when this process is successfully
completed, it starts executing from the first global statement
onward. However, if it encounters a subroutine or a block called
BEGIN
while parsing, it not only
compiles it, but also executes it right away,
before resuming the compilation of the rest of the file. A small
experiment underscores this point:
sub BEGIN { # can also just say BEGIN { }; the word "sub" is optional print "Washington was here \n"; } foo*** ; # Intentional error
This prints the following:
Washington was here syntax error at x.pl line 4, near "** ;" Execution of x.pl aborted due to compilation errors.
Whereas a program with a syntax error normally does not get executed
at all, a BEGIN
subroutine occurring before the
error will be executed.
Because a BEGIN
block gets executed even before
the compilation phase is over, it can influence the rest of the
compilation. If you want to hardcode an include path in your program,
here is how to do it:
BEGIN { unshift (@INC, "../include"); } use Foo; # Looks for Foo.pm in "../include" first
An easier approach is to use the lib
module that
is packaged with the Perl distribution:
use lib qw(../include); # prepends the directory to @INC
Just as you ...
Get Advanced Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.