BEGIN and END Blocks in Perl

You may define any number of code blocks named BEGIN and END in Perl programs, which act as constructors and destructors respectively.

BEGIN { ... }
END { ... }
BEGIN { ... }
END { ... }
  • Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed.
  • Every END block is executed just before the perl interpreter exits.
  • The BEGIN and END blocks are particularly useful when creating Perl modules.

Following example shows its usage −


 Live Demo

package Foo;
print "Begin and Block Demo\n";
   print "This is BEGIN Block\n"
   print "This is END Block\n"


When above code is executed, it produces the following result −

This is BEGIN Block
Begin and Block Demo
This is END Block