return 0 or return bare

Mallory van Achterberg stommepoes at stommepoes.nl
Thu Dec 13 08:39:34 GMT 2012


On Wed, Dec 12, 2012 at 07:09:55PM +0000, Peter Sergeant wrote:
> On Wed, Dec 12, 2012 at 6:14 PM, Gareth Harper <spansh+london at gmail.com>wrote:
> 
> > On 12 December 2012 17:57, Joseph Werner <telcodev at gmail.com> 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.
> > >
> >
> > I stand corrected.
> >
> 
> Don't stand corrected too quickly - the idea that you should always use a
> bare *return()* is far from universally accepted - you can bite yourself
> just as easily in reverse by using bare return, and getting an empty list
> where you expected a false or undefined value:
> 
> https://gist.github.com/4270506
> 
> The boolean argument is reaching, at best. Perl programmers frequently use
> numeric 0 as a false value, and yet no-one is saying you should write code
> like:
> 
> sub lock_count {
> if ( $lock_counter ) {
>  return $lock_counter;
> } else {
>  return;
> }
> }
> 
> "Just in case" someone has decided to take your input in to an array,
> before asking if lock_count is true.
> 
> If you're using a bare return then all your returns should be
> *wantarray*dependent, or you're making the code even less predictable
> - making the
> *return* of an undefined value the only context-dependent *return* in a sub
> is crazy talk!
> 
> The simple rule here is: write functions that return either a list, or a
> scalar, and not both, and be explicit in your function documentation which
> you're expecting to return.
> 
> -P


Aaron Crane had a nice talk about this at YAPC::EU and London Perl Workshop
http://programming.tudorconstantin.com/2012/11/london-perl-workshop-2012.html

Not sure if he has slides somewhere, but he specifically went after some stuff
in Damian's book.

-Mallory


More information about the london.pm mailing list