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

I often use 'die' function to print a message and the abort.

But 'die' function by default also prints the script name and the line at which 'die' function was used. For EG:

[some message] at i_want_to_live.pl line 13

I just want to print the message and abort. So how can I disable the script name and the line number that is printed with 'die' function.

Replies are listed 'Best First'.
Re: Customizing the 'die' funtion
by kennethk (Abbot) on Apr 26, 2010 at 18:34 UTC
    Rather than redefining die, you can suppress the script name and the line number in output simply by ending your error string with a new line, a la:

    die "No extra info\n";

    This also works for warn and is documented in die.

    You can literally redefine die (which is appropriate in other contexts) by putting an appropriate hook in %SIG, or you can shift in which package Perl considers the error to have occurred with carp and modifying the @CARP_NOT array appropriately.

      Actually, you can literally redefine die by... redefining die:
      local *CORE::GLOBAL::die = sub { "My version of die." }; # use it...
      You almost certainly want to do this instead of overriding $SIG{__DIE__}, since the latter doesn't stop exception handling, but just gives you a chance to do some stuff before die continues going about its business.
        Yes, you can also literally redefine die using a typeglob in a BEGIN block, but I would disagree that this is generally what one would want. If you want to prevent die from killing your script, I think it is far better to trap potential dies in eval blocks, since you won't violate assumptions made in code you are calling (like having an open fail and still trying to process input). If you are not calling any external code, there is (generally) no reason to be using die in the first place if you don't want to throw exceptions.

        Certainly in the case of the OP, there is no indication that the exception should be prevented.

Re: Customizing the 'die' funtion
by moritz (Cardinal) on Apr 26, 2010 at 18:29 UTC
    Just add a newline to the end of the error message. See also: die.
    Perl 6 - links to (nearly) everything that is Perl 6.
Re: Customizing the 'die' funtion
by zwon (Abbot) on Apr 26, 2010 at 21:47 UTC

    See CORE about how to override builtins

Re: Customizing the 'die' funtion
by nvivek (Vicar) on Apr 27, 2010 at 04:12 UTC

    If you don't want to print the script name by die function.You try the following.

    die "Message\n";

    If you want the particular error message why die occurred,you use the following.

    die "Message:$!\n";