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?
In the example in perlmod/Perl Modules there is a BEGIN block. I looked at
Share
You only need a
BEGINblock if you need to execute some code at compile time versus run-time.An example: Suppose you have a module
Foo.pmin a non-standard library directory (like/tmp). You know you can have perl find the module by modifying@INCto include/tmp. However, this will not work:The problem is that the
usestatement is executed at compile time whereas theunshiftstatement is executed at run time, so when perl looks forFoo.pm, the include path hasn’t been modified (yet).The right way to accomplish this is:
Now the
unshiftstatement is executed at compile-time and before theuse Foostatement.The vast majority of scripts will not require
BEGINblocks. A lot of what you need inBEGINblocks can be obtained throughuse-ing other modules. For instance, in this case we could make sure/tmpis in@INCby using thelib.pmmodule: