CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Regular Expressions: Re: [Wildcard] What are the meanings of blocks? : Edit Log

Veteran / Moderator

Sep 21, 2017, 10:12 AM

Views: 19756
Re: [Wildcard] What are the meanings of blocks?

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:

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

perl -nw -E 'BEGIN{my $total = 0;} chomp; $total += $_; END{ say "Total count is $total";}' numbers.txt

(This post was edited by Laurent_R on Sep 21, 2017, 10:14 AM)

Edit Log:
Post edited by Laurent_R (Veteran) on Sep 21, 2017, 10:14 AM

Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives