develooper Front page | perl.perl6.users | Postings from September 2022

Re: BEGIN {} question

Thread Previous | Thread Next
Ralph Mellor
September 4, 2022 11:24
Re: BEGIN {} question
Message ID:
On Sun, Sep 4, 2022 at 5:07 AM ToddAndMargo via perl6-users
<> wrote:
> For the fun of it, I placed a "booboo;"
> Interesting!

You might like to think of `BEGIN` as a signal to the "compiler":

"Please do more than just "compile" this code. Please also run it,
right now, before "compiling" any more code.".


Thus, when the "compiler" "compiles" the code below it will also "run"
enough of it to display "But this does".

    say "This doesn't appear";
    BEGIN {
      say "Nor this";
      BEGIN say "But this does";
    }}^%^& no matter what nonsense is here or below:

    BEGIN !& }}!!%^&

The "compiler" will then display "===SORRY!===" as it gets to the end
of the first outer `BEGIN` and realizes `booboo` hasn't been post declared
(so hasn't been declared at all).

At that point the "compiler" has already compiled `say "Nor this";` but it
does not run it. This is so despite that `say` having appeared in a `BEGIN`.
That's because the lack of a `booboo` declaration in that outer `BEGIN`
block is considered so important that the "compiler" immediately gives up
doing anything more whatsoever -- so no more compilation *or* running.

Once you understand it's just the "compiler" going sequentially through
the source code, doing what the code tells it to do, and recognizing that
code like `say 42` is telling the "compiler" to display `42` when that line
of code is supposed to run, and recognizing that `BEGIN say 42` tells
the "compiler" that the time when that code is supposed to run is ASAP,
it'll hopefully all seem as simple and nice as it in fact is.


I've "scare-quoted" "compiler", "compiles", and "run" in the above because:

* The Rakudo "compiler" is actually a combined compiler+runner

* In Raku, "compiles" includes "running" code that "runs" at "compile-time"

* "run" means executing code, but that can happen during "compilation"

(Perl has a similar scheme -- it has a similar `BEGIN` construct.)

(In theory, Raku code that's already been compiled ahead of time, and all
that's left is to run it, should significantly outperform Perl. In
practice, getting
to the point that this is generally true is a work in progress.)


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About