Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

DANGER - was Re: Re: Syntax Error Checking

by merlyn (Sage)
on Jan 01, 2001 at 22:04 UTC ( [id://49197]=note: print w/replies, xml ) Need Help??


in reply to Re: Syntax Error Checking
in thread Syntax Error Checking

That won't stop an embedded BEGIN block from executing.
my $coderef = eval <<'END'; sub { print "hello world\n"; BEGIN { print "you lose!\n"; } print "goodbye world\n"; } END
That prints "you lose". Too bad.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: DANGER - was Re: Re: Syntax Error Checking
by OeufMayo (Curate) on Jan 02, 2001 at 14:46 UTC

    Too bad, true. But I still don't understand why it doesn't print the two other lines.

    In my Great Foolishness(tm), I had always thought that there could only be one BEGIN block by package. So as I was reading merlyn's answer to the question, I thought to myself: "Ah! easy! I just have to embed the eval'd block in another BEGIN block, to make sure it'll be evaluated first."

    Alas, the "you lose!" block was the first printed in the block and then the "hello/goodbye" lines. Mmmh, too bad.

    Then, I realized that anything outside the BEGIN block in the sub was not executed.

    What is happening exactly? Does a BEGIN code inside a sub never returns? Can someone point me a node where all these mysteries are unveiled? Thanks!

    <kbd>--
    PerlMonger::Paris(http => 'paris.pm.org');</kbd>
      A BEGIN block is equivalent to a subroutine definition of a subroutine called BEGIN, followed immediately by an invocation and removal of that subroutine at compile time. So for example, in the case of:
      sub fred { blah blah; sub barney { print "hey there"; } foo foo; }
      we'd get the barney subroutine defined, with no connection (except closures if any) with the fred subroutine. Invoking fred would do nothing to or about barney. Replace barney with BEGIN, and you get the same behavior with respect to fred, except that BEGIN is now executed immediately even before compiling foo foo. Drop the "sub" keyword, and the same behavior applies.

      -- Randal L. Schwartz, Perl hacker

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://49197]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-26 09:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found