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 −

Example

 Live Demo

#!/usr/bin/perl
package Foo;
print "Begin and Block Demo\n";
BEGIN {
   print "This is BEGIN Block\n"
}
END {
   print "This is END Block\n"
}
1;

Output

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

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

Updated on: 02-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements