http://www.perlmonks.org?node_id=565165

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

hi monks,
what is the usage of die function with in eval and outside the eval.
how can i print script name and line number in the die function.

Replies are listed 'Best First'.
Re: die function
by Zaxo (Archbishop) on Aug 02, 2006 at 05:54 UTC

    The die function prints a message given by its arguments to STDERR and exits gracefully. The difference between having die inside and outside an eval block is that, inside, the exit is trapped at the next statement beyond the eval block, and the die message is placed in $@ instead of printing to STDERR. That allows recovery from error conditions, much like the try..throw..catch construct found in C++ and Java.

    To get the file and line number printed, just avoid an explicit newline at the end of the die message.

    If, in your shell, you say:

    $ perldoc -f die
    
    you'll get all this info and much more, straight from perlfunc.

    After Compline,
    Zaxo

Re: die function
by davorg (Chancellor) on Aug 02, 2006 at 07:57 UTC
    how can i print script name and line number in the die function

    As others have said, if you don't have a newline on the end of the message that you pass to die then you'll get a message of the form "{your message} at {filename} line {line number}". If you want to rearrange that format, you can do that using __FILE__ and __LINE__.

    die 'File: ', __FILE__, ' Line: ', __LINE__, " Oops!\n";
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: die function
by GhodMode (Pilgrim) on Aug 02, 2006 at 06:02 UTC

    You've got two questions there. I'm not sure I understand the first one, and I don't use eval much. So, I'll just try to answer the second one.

    By default, die adds the file name and line number to the end of whatever message you give it, but it takes it off if the message has a newline (\n) at the end.

    If you want to put the information somewhere in the middle of the message, the tokens __LINE__ and __FILE__ are the line number and filename. Use them like constants (outside of any quotes). $0 also contains the file name. If you're in a subroutine, you can use the caller function, which, if used in a list context, returns the package, file name, and line number that the current subroutine was called from.

    --
    -- Ghodmode
    
    Blessed is he who has found his work; let him ask no other blessedness.
    -- Thomas Carlyle