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;
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;
Erikr source share