Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Compilation phases: BEGIN, CHECK, INIT, END

  • BEGIN
  • CHECK
  • INIT
  • END
BEGIN {
    # do something here
}
* You can have more than one of each one

BEGIN  - execute as soon as possible (compiled)
CHECK  - execute after the whole script was compiled
INIT   - execute before running starts
END    - execute as late as possible (after exit() or die())

When running perl -c script.pl   both the BEGIN and CHECK blocks are executed.

perldoc perlmod
#!/usr/bin/perl
use strict;
use warnings;

END {
    print "END\n";
}

print "BODY\n";
my $x = 0;
print 1/$x;          # error the program stops working

print "AFTER ERROR\n";

BEGIN {
    print "BEGIN\n";
}

print "After BEGIN block\n";

BEGIN
BODY
Illegal division by zero at examples/other/begin_end.pl line 11.
END
#!/usr/bin/perl
use strict;
use warnings;

BEGIN {
    print "BEGIN\n";
}

CHECK {
    print "CHECK\n";
}


INIT {
    print "INIT\n";
}

END {
    print "END\n";
}

print "BODY\n";

BEGIN
CHECK
INIT
BODY
END