Hello there! Regarding blocks, I know how to code them, that BEGIN and INIT run the other way than CKECK and END, but I have no clue how I can properly include them into a programm. What is the main use of such blocks in Perl, can someone explain me with few examples? Are they some kind of subroutines, because it seems so... kinda... Are they mainly used for performance preferences, when compiling huge bulk of programm codes?

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):