Question perlmod

In the example in perlmod / Perl Modules there is a BEGIN block. I looked through some modules, but none of them had a BEGIN block. Should I use such a BEGIN block when writing a module or is it not available?

+4
source share
2 answers

You only need a BEGIN block if you need to execute some code at compile time compared to runtime.

Example. Suppose you have a module Foo.pm in a non-standard library (e.g. /tmp ). You know that Perl can find a module by changing @INC to /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, while the unshift is executed at runtime, so when perl searches for Foo.pm , the inclusion path has not yet been changed (yet).

The correct way to accomplish this is:

 BEGIN { unshift(@INC, '/tmp') }; use Foo; 

The unshift statement is unshift executed at compile time and before the use Foo statement.

The vast majority of scripts will not require BEGIN blocks. Much of what you need in BEGIN blocks can be obtained through use in other modules. For example, in this case, we could verify that /tmp is in @INC using the lib.pm module:

 use lib '/tmp'; use Foo; 
+8
source

The BEGIN block in the module is completely free. You only use it if something needs to be done by your module when loading it before using it. In this case, there is rarely much, so you can rarely use the BEGIN block.

+2
source

All Articles