Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Die and Exit Codes

by pileofrogs (Priest)
on Nov 30, 2006 at 20:16 UTC ( [id://587040]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://587040]
Approved by Albannach
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-03-28 17:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found