Dinesh Gowda
Dinesh Gowda

Reputation: 1154

Exit Codes when using die in Perl

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.

Upvotes: 3

Views: 8724

Answers (2)

janh
janh

Reputation: 2982

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.

Upvotes: -2

choroba
choroba

Reputation: 242218

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.

Upvotes: 8

Related Questions