in reply to What should be returned in scalar context?

I think that use of wantarray() to modify return behavior should be generally avoided. In my opinion it is a clear violation of the principal of least surprise.

As an example, consider this real-world case from Bricolage:

@stories = Bric::Biz::Asset::Business::Story->list(); if (not @stories) { print "There are no stories.\n"; }

That works fine, but this doesn't:

if (not Bric::Biz::Asset::Business::Story->list()) { print "There are no stories.\n"; }

That's because Bricolage list() methods (and lots of other Bricolage methods) try to be helpful and return array refs in scalar context. I've personally found a number of bugs that turned out to be caused by this problem, and I'm sure there are more waiting to be found.

There may be cases where wantarray() is useful, but I definitely don't consider it a general-purpose tool.

-sam

Replies are listed 'Best First'.
Re: Re: What should be returned in scalar context?
by Joost (Canon) on Dec 03, 2003 at 20:22 UTC
    I think that use of wantarray() to modify return behavior should be generally avoided. In my opinion it is a clear violation of the principal of least surprise.
    This obviously depends on what exactly is being returned in the first pace, but in general I agree. When you don't have any particular reason to think about context, don't use wantarray. I find that, often, the 'problem' solves itself without me thinking about it.

    Having said that, I do use wantarry sometimes, and my reasons are usually effiency related:

    • Runtime efficiency

      Returning an arrayref instead of a list, thus avoiding copying many scalars. Well, we can't agree on everything :-)
    • Programmer efficiency

      Using count(*) instead of select( values ... ) in an SQL query, if you only want to know the number of rows matching. This saves the user from having to remember yet another subroutine/method name, and me from having to put the WHERE clause in 2 places (or factoring it out).

      Also, it seems like a better idea than just returning the last column, or the number of columns, or anything like that, which would likely be the result of not using wantarray in this case.

    There might be better examples, but I'm too lazy to think of them now.

    Joost.

    -- #!/usr/bin/perl -w use strict;$;= ";Jtunsitr pa;ngo;t1h\$e;r. )p.e(r;ls ;h;a;c.k^e;rs ";$_=$;;do{$..=chop}while(chop);$_=$;;eval$.;