Pungs
Pungs

Reputation: 2552

Perl sigdie handler and eval

I am overriding my SIG die handler as below inside my Logger module.

# Catch die messages and log them with logdie
$SIG{__DIE__} = \&logdie;

Now below program run as expected and post processing will be called.

use strict;
use warnings;
use File::Path;
# use MyLogger;

my $dir="/random";
eval {
  # local $SIG{__DIE__};
  File::Path::make_path($dir);
};
if($@) {
 warn("Cannot create $dir :$@ \n");
}
print "Post processing \n";

However, if i include my logger module and add use MyLogger the code fails inside eval statment with below error and post processing is not called.

[ERROR] 2015/04/27 22:19:07 Carp.pm:166> mkdir /random: Permission denied at ./test.pl line 11.

One option to fix this to add a local sigdie handle (as shown in commented code).

However, my logger module is used by many scripts.

Is there a way to modify my Logger module so that it supresses ERROR message when called from inside eval block ?

Upvotes: 3

Views: 434

Answers (1)

mob
mob

Reputation: 118665

The $^S indicates whether the current execution point is inside of an eval block:

$^S         State
---------   -------------------------------------
undef       Parsing module, eval, or main program
true (1)    Executing an eval
false (0)   Otherwise

So it sounds like you want to check whether $^S is true at the beginning of your __DIE__ handler:

package MyLogger;
sub logdie {
    $^S && die $_[0];    # use default die handler
    ...                  # else use custom die handler
}

Upvotes: 7

Related Questions