Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perlmod question

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?

like image 473
sid_com Avatar asked Dec 28 '22 15:12

sid_com


1 Answers

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;
like image 166
ErikR Avatar answered Dec 30 '22 04:12

ErikR