Why did you insert this post in the Regular Expression section of this forum?

A BEGIN block is executed as soon as the compilation of such block is finished, i.e. before the compilation of the rest of the program. A CHECK or INIT block is executed immediately after the end of the compilation of the program, before any other code (except code in a BEGIN block, if any).

They can be used when you need to set up something before starting.

An END block executes when the program terminates. This may be handy when you do need to do some cleanup before actually terminating the program, even if it terminates early upon an error.

These blocks are relatively rarely used, because there are usually other ways to do that, or Perl can take care of it for you.

For example, upon completion ofg the program, you might want to close file handles, disconnect from a database or destroy objects, but you don't actually need to do it, Perl will usually do it for you. But you might want to use an END block to commit changes to a database if you don't have autocommit.

A BEGIN block may be used to include into your code a library that needs to be there to be able to compile what comes next. Again, this is not needed with a use statement.

So, these blocks are quite rarely needed.

These blocks can be quite useful, though, in Perl one-liners using the -n or -p command-line options. For example, you might count the lines of a file like this:

Code

perl -nE 'END{say $.}' name_of_file.txt

The -n option tells read the file line by line, and the END block prints $., the number of lines read. But there are usually simpler ways to count the lines of a file (such as wc under *nix environments).

A less contrived and more useful use might be to sum up a list of numbers contained in a file (one number per line):