lauragarcia has asked for the wisdom of the Perl Monks concerning the following question:

Does the BEGIN block used to to catch compile-time warnings

BEGIN { use CGI::Carp qw(carpout); open(LOG, ">>/var/local/cgi-logs/mycgi-log") or die "Unable to append to mycgi-log: $! "; carpout(*LOG); }

have to completely enclose the entire script it's tracking or can the BEGIN block appear as such at the top of the script?
(Apologies in advance for the dimwittedness of this question, but at least it should be easy to answer!)
Thanks so much,

Replies are listed 'Best First'.
Re: CGI::Carp use of BEGIN block to log errors (newbie question)
by arturo (Vicar) on Apr 23, 2001 at 21:21 UTC

    BEGIN just has to enclose the stuff you want executed after the script is compiled(update which is false, as tye points out), but before the rest of it starts executing. The block should contain only that code that should execute first.

    Perl compiles the script into what's called 'bytecode', then it executes that bytecode. So it's unlike a pure interpreted language which handles things line-by-line.

    Since the whole script is compiled before anything is executed (update oops, this is false, but the next sentence isn't, which is sufficient to answer the question), BEGIN can appear anywhere in your source code, but will be executed before anything else in the script is. Of course it's good practice to put it up at the top of the script. to avoid confusing anyone that has to maintain the code!

      No, a BEGIN block is executed before the rest of the script is compiled.

      To avoid confusion, the answer to the original question is correct: The BEGIN block doesn't need to enclose the entire script.

              - tye (but my friends call me "Tye")
      To add to arturo's response, BEGIN blocks are processed in the order in which they're encountered during compilation. Not a problem if you only have one BEGIN block, but since you're acquiring an external resource (opening a file), you might need to pay attention to the order of multiple blocks.

      Also, consider adding

      END { close(LOG); }
      END blocks are queued up and are executed in reverse (LIFO) order.

Re: CGI::Carp use of BEGIN block to log errors (newbie question)
by providencia (Pilgrim) on Apr 23, 2001 at 21:54 UTC