in reply to Exiting script from subs

Generally, if you're exiting within a subroutine, you're doing so for some abnormal reason, so die() is perfectly appropriate. Personally, I would expect to see the second version if the script termination is the standard processing mode.

Replies are listed 'Best First'.
Re^2: Exiting script from subs
by bradcathey (Prior) on Apr 15, 2005 at 13:05 UTC

    Question, as it has come up in this thread twice, and that is the issue of die() vs exit((). The Camel states that one should not exit a subroutine when an error needs to be trapped. But if not, is die necessary, or is exit sufficient?

    Comments?


    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot
      What the Camel does or doesn't say is mostly irrelevant. If your coding standards allow for exit() within a subroutine, then use it. However, most of the community has come to expect die() within subroutines and exit() (if it's even used) from the main scope.

      Now, die() and exit() do different things. The biggest difference is

      eval { print "Inside\n"; die; }; print "Outside\n"; ---- Inside Outside
      vs.
      eval { print "Inside\n"; exit; }; print "Outside\n"; ---- Inside
      exit() exits, end of story. die() allows for some manner of error trapping. This is the main reason why die() is preferred within subroutines. You may want to reuse that subroutine somewhere else that wants to be able to trap the abnormal termination. Also, die() triggers $SIG{DIE}, which can also be useful to trap.
        You can trap an exit (termination of a script) as well.
        END { print "Outside"; } eval { print "Inside\n"; exit; }; print "Outside\n"; ---- Inside Outside
        -- gam3
        A picture is worth a thousand words, but takes 200K.

      I would say not, for one thing it limits the possibility of reuse in your code if you are to issue the untrappable exit() in your subroutine.

      /J\