On Fri, Sep 26, 2003 at 11:04:21AM -0400, Dan Anderson wrote:
> > BEGIN blocks do not take precedence over one another--they are all
> > still executed.  They are, however, executed immediately after perl
> > finishes compiling them.  So, if you have the following code:
> 
> Ok, so I'm guessing that the reason that 3214 is displayed is not
> because of precedence, but that every begin block is pushed into a stack
> of some kind, and when perl starts executing code, code on the top of
> the stack ends up being run first.  Is that right?
> 
> So it's sort of like precedence but really isn't.  Which explains when
> things printed off are printed off from innermost begin to outermost
> begin, but a subroutine declared in a begin nested in other begins
> creates an error when called before the sequence in the code.
> 
> Correct?


Close; it's not precedence, it's just order of execution.  Much like
in math, you do multiplacation before addition--here, you do BEGIN
blocks as soon as possible, then you do "normal" code.  Let me clarify
my earlier example, and maybe that will help.

1 { # (Block Outer)
2    print "A\n"; # Will be executed at runtime (since not in BEGIN block)
3    foo(); # Also a run-time execution; Not defined yet, but that's ok
4
5    BEGIN {  # (Block 1)
6        print "B\n";  # Not finished compiling block yet, so not printed
7        BEGIN {  # (Block 2)
8            print "C\n"; # Not finished compiling block yet, so not printed
9            sub foo { print "D\n"; }
10       }
         # Finished compiling block 2, so print C
11   }
         # Finished compiling block 1, so print B
12 }
RUNTIME BEGINS HERE: print A, then call foo() which prints D

Another way to say that: When perl goes to compile/execute this, it
does so in the following order (pseudocode):

____
open block Outer;
compile line 2, to be executed at runtime
compile line 3, to be executed at runtime
open block 1;
compile line 6, to be executed as soon as Block 1 finishes compilation
open block 2;
compile line 6, to be executed as soon as Block 2 finishes compilation
compile line 7, to be executed as soon as Block 1 finishes compilation
compile line 8, to be executed when called
close block 2
execute line 8                                 -> C
close block 1
execute line 6                                 -> B
BEGIN RUNTIME
execute line 2                                 -> A
execute line 3 (call line 'foo()' on line 9)   -> D
close block Outer;
____


Does that help?

--Dks

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to