3

I have overridden die in perl for my logging framework, so that it can log messages and print it on console.

Overridden code for die:

BEGIN{ *CORE::GLOBAL::die = sub { 
        my ($package, $filename, $line, $subroutine) = caller;
        untie *STDERR;
        my $message;
        foreach my $arg (@_) {
            $message = $message.$arg;
        }

        print STDERR $message;
        tie *STDERR, __PACKAGE__, (*STDERR);
        logmessage("die",$message,$filename, $line);
        #What exit code to pass?
        #exit CODE;
    }
}

I don't know what exit code to set while exiting the process as the normal die exits with an error code.

  • Is there any way I can find out what exit code to set when die is called?

  • Also It would be helpful if can know the list of error codes availabe in perl?

3
  • 2
    Note that die() just throws an exception that can be caught later with eval { ... }. A die() should not directly terminate the program!
    – amon
    Commented Oct 5, 2017 at 9:17
  • 4
    Sidenote: see also if $SIG{__DIE__} could suit your needs.
    – PerlDuck
    Commented Oct 5, 2017 at 9:21
  • Ok i will check that Commented Oct 5, 2017 at 9:27

2 Answers 2

8

The exit code is documented in die:

 exit $! if $!;              # errno
 exit $? >> 8 if $? >> 8;    # child exit status
 exit 255;                   # last resort

But as @amon noted, die doesn't exit, it throws an exception. Instead of overriding it, it might be clearer to wrap the whole thing into an eval { ... ; 1 } (or Try::Tiny's try) and log the exception in the or do or catch part.

9
  • Since die is overridden what exception to throw from my die? Commented Oct 5, 2017 at 9:32
  • 1
    It starts with "instead of overriding", so there's no "my die".
    – choroba
    Commented Oct 5, 2017 at 9:52
  • problem is my project has already 300 perl files and I cant wrap each and everywhere in all those files. So i need to override it if i want log messages into my logging framework Commented Oct 5, 2017 at 9:54
  • 1
    Then $SIG{__DIE__} might be more suitable.
    – choroba
    Commented Oct 5, 2017 at 9:58
  • 2
    You can use $SIG_{__DIE__}. But please, put the code into a single module and load it from all the scripts instead of inserting the code into each of them.
    – choroba
    Commented Oct 5, 2017 at 10:12
-2

die() exits with a none-zero exit code (but it's not defined, which, I believe):

jan@jancooltek ~ $ perl
die("test");
test at - line 1.
jan@jancooltek ~ $ echo $?
9

However, with -e:

jan@jancooltek ~ $ perl -e 'die("test")'
test at -e line 1.
jan@jancooltek ~ $ echo $?
255

exit() can use any exit code you'd like, there are no specific rules in Perl. Settle on something != 0 and use that for these generic errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.