What is the role of the BEGIN block in Perl?

Viewed 24775

I know that the BEGIN block is compiled and executed before the main body of a Perl program. If you're not sure of that just try running the command perl -cw over this:

#!/ms/dist/perl5/bin/perl5.8

use strict;
use warnings;

BEGIN {
    print "Hello from the BEGIN block\n";
}

END {
    print "Hello from the END block\n";
}

I have been taught that early compilation and execution of a BEGIN block lets a programmer ensure that any needed resources are available before the main program is executed.

And so I have been using BEGIN blocks to make sure that things like DB connections have been established and are available for use by the main program. Similarly, I use END blocks to ensure that all resources are closed, deleted, terminated, etc. before the program terminates.

After a discussion this morning, I am wondering if this the wrong way to look at BEGIN and END blocks.

What is the intended role of a BEGIN block in Perl?

Update 1: Just found out why the DBI connect didn't work. After being given this little Perl program:

use strict;
use warnings;

my $x = 12;

BEGIN {
    $x = 14;
}

print "$x\n";

when executed it prints 12.

Update 2: Thanks to Eric Strom's comment below this new version makes it clearer:

use strict;
use warnings;

my $x = 12;
my $y;

BEGIN {
    $x = 14;
    print "x => $x\n";
    $y = 16;
    print "y => $y\n";
}

print "x => $x\n";
print "y => $y\n";

and the output is

x => 14
y => 16
x => 12
y => 16

Once again, thanks Eric!

3 Answers
Related