in reply to What can we assume in a BEGIN block ?

"Normally, while parsing a file, Perl compiles the entire code, and when this process is successfully completed, it starts executing from the first global statement onward. However, if it encounters a subroutine or a block called BEGIN while parsing, it not only compiles it, but also executes it right away, before resuming the compilation of the rest of the file." So if I'm reading this right, everything inside the BEGIN block runs first, regardless of where the BEGIN block is located in the program.
  • Comment on Re: What can we assume in a BEGIN block ?

Replies are listed 'Best First'.
Re^2: What can we assume in a BEGIN block ?
by herveus (Prior) on Oct 04, 2004 at 11:29 UTC
    Howdy!

    That would be spot on!

    The call to _initialize occurs at compile time, but the initialization part of the "our" statement occurs at run time.

    yours,
    Michael
      OK, so now I know I really dont get it.

      What variable got incremented at compile time ? If the "our $initialised" doesnt happen till run-time, what did we increment during the BEGIN?

      use brain;

        The variable $initialized was declared by the my $initialized. This made it known the parser so when the source code farther down saw it, it incremented the variable. At the time, the value was still undefined because while the variable had been declared, the = 0; hadn't run yet. So now $variable = 1 after the BEGIN. Now that the file is finished being parsed, execution starts at the top so now you run $initialized = 0;.

        $variable := undef -> 1 -> 0

Re^2: What can we assume in a BEGIN block ?
by leriksen (Curate) on Oct 04, 2004 at 11:27 UTC
    OK, I may be focussing too closely here

    if it encounters a subroutine or a block called BEGIN while parsing...

    what happens to everything it has parsed upto the BEGIN block - does it forget about it till the begin has been completed. The doc says 'parsed' - does that mean entries in the symbol table etc have been made too ?

    use brain;