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

I'm writing a function that I would like to respond to the same error conditions by both die()ing and exiting with specific exit codes. Is there a way to set the exit code with die?

Here's why I want this. I'm writing some nagios plugins. Nagios plugins are scripts that communicate broad status informaion with the script's exit code, and detailed status information with STDOUT. I'm writing several of these things and I'm trying to re-use my code by putting it into modules. Sometimes, I want to catch certain errors and other times I want the same errors to make the script die. If I use die(), I can't set the exit code, so I can't communicate the broad status info. If I use exit(), I can't catch the error.

Thanks!
-Pileofrogs

Replies are listed 'Best First'.
Re: Die and Exit Codes
by rhesa (Vicar) on Nov 30, 2006 at 20:54 UTC
    Read perlfunc :) It states:
    die LIST
    Outside an "eval", prints the value of LIST to "STDERR" and exits with the current value of $! (errno). If $! is 0, exits with the value of "($? >> 8)" (backtick ‘command‘ status). If "($? >> 8)" is 0, exits with 255.
    Example:
    rhesa@schutz:~$ perl -e '$!=3; die "whoa: $!"' whoa: No such process at -e line 1. rhesa@schutz:~$ echo "exit=$?" exit=3
      Oh, for some reason I was convinced i couldn't set $!...

      Thanks!
      --Pileofrogs

Re: Die and Exit Codes
by ikegami (Patriarch) on Nov 30, 2006 at 20:27 UTC

    Maybe you could use $^S to see if you're in an eval. For example,

    DieWithCode.pm:

    use strict; use warnings; package DieWithCode; BEGIN { our @EXPORT = 'die_with_code'; require Exporter; *import = \&Exporter::import; } use Carp qw( carp croak ); sub die_with_code { my $code = shift(@_); if ($^S) { croak(@_); } else { carp(@_); exit($code); } } 1;

    Update: Made it into a module so carp and croak would print the right line number.

Re: Die and Exit Codes
by jdporter (Paladin) on Nov 30, 2006 at 20:39 UTC

    This will work for simple scripts, at least. Not sure how scalable it is.

    { my $exit_code = 0; END { $! = $exit_code } sub die_with_code { $exit_code = shift; die @_ } } die_with_code( 3, "yowch!\n" );
    We're building the house of the future together.