in reply to Re: Mini-rant about 'strict'
in thread Mini-rant about 'strict'

I know that BEGIN is not really a sub but it's kind of a sub ... I wonder why that doesn't work? Is it some sort of weird timing issue?

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re^3: Mini-rant about 'strict'
by Aristotle (Chancellor) on Aug 04, 2004 at 22:25 UTC

    It's not even a kind of sub. It's not anything like a sub at all. You can't manually call the code found in a BEGIN block, can't take a reference to it, or anything else you can do with a sub. The fact that you're allowed to write sub BEGIN is just syntactic sugar — badly misguided syntactic sugar.

    Makeshifts last the longest.

      Eh. People probably shouldn't do this anyway but it is possible.

      use B; BEGIN { B::save_BEGINs() } BEGIN { "Boo!" } print $_->object_2svref->() for B::begin_av->ARRAY; # Corrected by adding ->ARRAY. I forgot that begin_av does not return # a list, it returns a [cpan://B]::AV object which must have ->ARRAY # called on it to get the contents.

        That gives me Not a CODE reference because B::begin_av returns an array ref. And the array is empty.

        Even if that code worked, it wouldn't really prove much. BEGIN blocks still don't behave like subs, even though you can use introspection magick to cast an elephant into a mouse. The existence of PadWalker doesn't make lexicals globals either.

        Makeshifts last the longest.

      You can return from it. Modifications to @_ inside a BEGIN block disappear after leaving the BEGIN block. Also, (caller(0))[3] returns "main::BEGIN" inside BEGIN blocks.

      # Prints nothing BEGIN { @_ = 1 } print @_; # Prints 1 BEGIN { print 1; return; print 2; } # Prints main::BEGIN BEGIN { print +(caller(0))[3] } # (Un)expectedly, this won't recurse BEGIN { &BEGIN }
      I'd say it behaves quite a bit like a subroutine, albeit not completely.

      ihb

      Read argumentation in its context!