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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With