boolean return (was Re: cpan you have to see)
DAVID HODGKINSON
davehodg at gmail.com
Wed Dec 12 21:40:27 GMT 2012
On 12 Dec 2012, at 21:17, Uri Guttman <uri at stemsystems.com> wrote:
> On 12/12/2012 12:57 PM, Joseph Werner wrote:
>> On Wed, Dec 12, 2012 at 12:45 PM, Gareth Harper <spansh+london at gmail.com> wrote:
>>
>> PBP and I disagree with you on this one, Gareth. When a sub does a
>> "return 0;" to a list context, that is interpreted as true. A bare
>> "return;" is best practice.
>
> and i support that as well. the argument i get from the other side is when calling foo() in a list context that needs a scalar like a hash value:
>
> sub foo { ... return if $bad }
> %bar = ( foo => foo() ) ; # fail
>
> my counter answer is to use scalar there:
>
> %bar = ( foo => scalar foo() ) ;
>
> the win here is letting the caller decide on the context of the boolean return. if you do a return undef (or 0 or '') then the caller can't ever use the sub in a list context expecting an empty list, it always gets a scalar. a plain return works in all contexts and lets the caller force a scalar when needed.
Coming from a strongly-typed background (C, C++), this bisexuality
of returns seems error prone to me. My gut instinct is to have two
subs, if necessary with one _as_scalar and one _as_hash. Clear, separate
and less open to errors like these.
Am I missing some kind of magic here?
More information about the london.pm
mailing list