Reputation: 25107
In the example in perlmod/Perl Modules there is a BEGIN
block. I looked at some modules but none of these had a BEGIN
block. Should I use such a BEGIN
block when writing a module or is it dispensable?
Upvotes: 4
Views: 94
Reputation: 52029
You only need a BEGIN
block if you need to execute some code at compile time versus run-time.
An example: Suppose you have a module Foo.pm
in a non-standard library directory (like /tmp
). You know you can have perl find the module by modifying @INC
to include /tmp
. However, this will not work:
unshift(@INC, '/tmp');
use Foo; # perl reports Foo.pm not found
The problem is that the use
statement is executed at compile time whereas the unshift
statement is executed at run time, so when perl looks for Foo.pm
, the include path hasn't been modified (yet).
The right way to accomplish this is:
BEGIN { unshift(@INC, '/tmp') };
use Foo;
Now the unshift
statement is executed at compile-time and before the use Foo
statement.
The vast majority of scripts will not require BEGIN
blocks. A lot of what you need in BEGIN
blocks can be obtained through use
-ing other modules. For instance, in this case we could make sure /tmp
is in @INC
by using the lib.pm
module:
use lib '/tmp';
use Foo;
Upvotes: 8
Reputation: 753455
A BEGIN block in a module is entirely dispensable. You only use it if there is something that must be done by your module when it is loaded, before it is used. There are seldom reasons to do much at that point, so there are seldom reasons to use a BEGIN block.
Upvotes: 2