in reply to Entering and exiting subs in style

Regarding #1, there are bound to be occasions where a sub may encounter a condition that really must bring the whole process to a halt. In such cases, "die" (or "croak") would be more appropriate than "exit".

But even when such a condition might arise, you should choose consciously between dying within the sub vs. returning an error status to the caller. The former choice is typical of one-shot (or "application-specific") code -- the functionality of the sub is so tightly bound to the specific script/app that you wrote it for, it's okay for the sub to exercise this level of control over the entire app.

On the other hand, if you're writing a sub because it's likely to be useful in a number of different situations, you'll probably be better off having it return to the caller in all cases -- some day you'll want the flexibility of letting the caller decide what to do when the sub hits a given problem. (Then again, if you know the sub will die under certain conditions, the caller can wrap the sub in an "eval" to trap these conditions -- this is also a perfectly legitimate design choice, so long as you document it.)

As for #2, there are obviously some rarified situations where the magical trappings of goto &some_sub are needed (or at least very convenient) -- otherwise it wouldn't have been added to the language. But I find it hard to imagine situations like that arising in day-to-day application development (which is where I spend most of my programming time). If you're mucking with perl internals (e.g. replacing/enhancing core functions in some subtle, intricate way), or just trying to deepen you obfu skills, sure, it will be handy. But most of the time, there probably isn't any really good reason to use it.

Replies are listed 'Best First'.
Re: Re: Entering and exiting subs in style
by bradcathey (Prior) on May 26, 2004 at 12:04 UTC
    Thanks, monks, for the thorough replies--very helpful. One thing I heard was "die" vs "exit." I have always associated "die" with errors related to internal operations, such as file handling, etc. So, I checked with perldocs on the issue of exit and found this concurring advice:
    Don't use exit to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use die instead, which can be trapped by an eval.
    So, better to "die" than just "exit." Sounds a bit too final ;^) but I'll defer to this advice.

    —Brad
    "A little yeast leavens the whole dough."