return 0 or return bare
pierre masci
piemas25 at gmail.com
Thu Dec 13 11:29:55 GMT 2012
Here is my (very short) summary of this talk :
- don't use context-sensitive subroutines !
- throw an exception if a list function is called in scalar context :
confess "list-returning subroutine called in scalar context" if !wantarray;
And now i'm thinking that a scalar function should maybe throw an exception
when called in list context; for the reason mentioned above. It just feels
a bit heavy, to check for each scalar function that it is called in scalar
context. One might say : it's just one line per function; i'll just add it
to my function-creation template in Vim.
On Thu, Dec 13, 2012 at 8:39 AM, Mallory van Achterberg <
stommepoes at stommepoes.nl> wrote:
> 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