boolean return (was Re: cpan you have to see)

Abigail abigail at
Wed Dec 12 21:31:37 GMT 2012

On Wed, Dec 12, 2012 at 04:17:28PM -0500, Uri Guttman 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> 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.

The flip side of this dogma is, you end up with code like:

    sub foo {
        return unless $result;
        return $result;

with people calling it like:

    my @foo = (scalar foo (1), scalar foo (2));

just in case someone at sometime wants to call this in list context
and then have an empty list.

That's a price I'm not willing to pay. Foreach function, I will make
a pragmatic choice, in some cases a plain return is the way to go,
and sometime it isn't.

Dogmas are useful for novices; and people following dogmas will have
a hard time to get past me if they get interviewed by me.


More information about the mailing list