in reply to Croak, return et al.

You can see that I could use eval (commented out) but again, I am unsure of the best practice!?

That's how I'd do it: die (or croak) in your module if necessary, and have the caller wrap the call in question in an eval to catch the exception (since that's what it really is).

Of course this can get cumbersome, so if your subroutine can only return certain values (e.g. only values that are true), you could also return false or undef, and have the caller invoke it like this:

$splat->splat() or die "splat() returned false"; unless(defined $splat->splat()) { die "splat() returned undef"; }

(Hmm, it sure would be nice if perl had a defined-or version of the or operator.)

Whether this is feasible depends on what splat() is supposed to be return, of course. For numbers there's a trick: you can return a string along the lines of "0 but true"; this'll numify to zero, but evaluate to true in boolean contexts. For strings, I don't think there's any such trick for the empty string.

There is no single best solution; it's a matter of taste.

Replies are listed 'Best First'.
Re^2: Croak, return et al.
by Laurent_R (Canon) on Aug 16, 2014 at 17:59 UTC
    For numbers there's a trick: you can return a string along the lines of "0 but true"; this'll numify to zero, but evaluate to true in boolean contexts. For strings, I don't think there's any such trick for the empty string.

    That's the semi-predicate problem. If a function is supposed to return a string, which may be empty without this being an error, and may also have to return failure, one way to make the distinction is to return a reference to the string rather than the string itself (a reference will always be true even is the string is empty) and undef when the function fails.

    I had to do something similar recently where a function had to return an array (and returning an empty array was not supposed to be an error). I just decided to return a reference to the array or undef when the input was exhausted (failure). This way I could distinguish between the three different cases and act accordingly

      Oh, that's clever! I'll have to remember that.