Begin at the BEGIN and go on till you come to the END: then stop.

In Perl we can run user defined code blocks at different stages when running a program.

  1. BEGIN blocks are run as soon as Perl finds them. If there is more than one block they get executed in the order they are found.
  2. CHECK blocks are run as soon as Perl finishes compiling. If there is more than one CHECK block they get executed in the reverse order they are found.
  3. INIT blocks are executed after CHECK blocks, and if more than one exists they get executed in the order they appear.
  4. END blocks get executed before the program finishs running, and no errors where found. If more than one END block is found they are executed in the reverse order they appear.
END { print "Twelve\n"; }
BEGIN { print "One\n"; }
CHECK { print "Six\n"; }
INIT { print "Seven\n"; }
BEGIN { print "Two\n"; }
END { print "Eleven\n"; }
CHECK { print "Five\n"; }
INIT { print "Eight\n"; }
BEGIN { print "Three\n"; }
INIT { print "Nine\n"; }
CHECK { print "Four\n"; }
END { print "Ten\n"; }


When we run the script it prints someting like:

$ perl blocks.pl
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
Ten
Eleven
Twelve

2 Comments

Playing with this I found that GitHub didn't highlight CHECK and INIT blocks. So I patched it.

You left out the new UNITCHECK block. From perldoc perlmod:

"UNITCHECK" blocks are run just after the unit which
defined them has been compiled.  The main program file
and each module it loads are compilation units, as are
string "eval"s, code compiled using the "(?{})" construct
in a regex, calls to "do FILE", "require FILE", and code after
the "-e" switch on the command line.

Leave a comment

About smash

user-pic I blog about Perl.