Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

BEGIN, eval {} and $^S

by eclark (Scribe)
on Dec 17, 2003 at 00:13 UTC ( #315182=perlquestion: print w/replies, xml ) Need Help??

eclark has asked for the wisdom of the Perl Monks concerning the following question:

According to perlvar, $^S has three states: true, false or undefined. True inside eval, false elsewhere, or undefined if parsing is not finished. This has the effect of $^S always being undef when die occurs in a BEGIN block (or use.) I'm stuck at this point, so I need to find a way around it.

How do I know if my DIE handler is being called within an eval when parsing is not yet complete?

BEGIN { $SIG{__DIE__} = sub { die @_ if $^S; # dont mess with eval. # custom handler code... exit(0); } eval { die 'another day'; }; if ($@) { # execution never happens }; } eval { die 'to day good'; }; if ($@) { # this works };

Replies are listed 'Best First'.
Re: BEGIN, eval {} and $^S
by diotalevi (Canon) on Dec 17, 2003 at 00:39 UTC
      Thats a good idea, I will use it in the future. It doesn't solve my problem because the DIE handler still wont know if it was called within eval or not.
        I think you'll have to pass that state to yourself via a global. How about something like $^S_FOR_REAL_AND_FOR_TRUE? You'd set it to something true prior to entering eval-string and clear it afterwards. You can inspect that during $SIG{__DIE__}.
Re: BEGIN, eval {} and $^S
by ysth (Canon) on Dec 17, 2003 at 08:02 UTC
    You want something like:
    sub in_eval { my $i=0; while (my @caller=caller($i++)) { return defined $caller[6] ? "eval EXPR" : "eval BLOCK" if !$caller[7] && $caller[3] eq "(eval)" } } ... die @_ if defined $^S ? $^S : in_eval;
    See perldoc caller for explanation. (I seem to recall there may be times when $^S is inaccurate; if so, just use die @_ if in_eval.)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://315182]
Approved by pfaut
Front-paged by bart
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2022-05-23 15:12 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (82 votes). Check out past polls.