in reply to Re: Croak, return et al.
in thread Croak, return et al.

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

Replies are listed 'Best First'.
Re^3: Croak, return et al.
by AppleFritter (Vicar) on Aug 16, 2014 at 19:22 UTC
    Oh, that's clever! I'll have to remember that.