So is wantarray() bad or not?

The style of returning different things in list vs scalar context has been debated for a long time (for a particular example, this thread in Perlmonks).

A few months ago I made a decision that all API functions in one of my projects should return this:

return wantarray ? ($status, $errmsg, $result) : $result;

That is, we can skip error checking when we don't want to do it.

Now, in the spirit of Fatal and autodie, I am changing the above to:

return wantarray ? ($status, $errmsg, $result) :
do { die "$status - $errmsg" unless $status == SUCCESS; $result };

But somehow I can still see myself and others tripping over this in the future, as I have, several times so far. It's bad enough that for each API function one already has to remember the arguments and their types, and one kind of return and its type.

Maybe I should just bite the bullet and admit the misadventure into wantarray(), and that context-sensitive return should be left to @foo, localtime(), and a few other classical Perl 5 builtins that have been ingrained in every Perl programmer's mind.

5 Comments

I think exceptions (try - catch) are a better approach than return codes

Well, you have to be aware of context in either event. The only thing that confuses me about the first case is that it's superfluous: If you return a list from your method and your calling context expects a scalar, you're going to get the last item in the list, $result, without any need for wantarray.



You should use wantarray if it is, you know, useful. If you really want your app to die if you encounter an error and your calling context isn't going to see it, then do it. If you find that behavior annoying and difficult to remember, then don't do it.

I know it's a cliche, but I'll say it anyway: wantarray is just a tool. Tools are neither good nor bad. It's how you use them. For free, I'll throw in my $0.02 that I haven't found any compelling uses for wantarray, but maybe I'm just not being creative enough ;)

I don't see a general problem with using wantarray to return different things as in your initial example, but using it for anything other than altering the return value seems very bad to me. For example, returning either an array or its last value based on wantarray is very useful in some cases. However, using it to determine if you use exceptions or not (as in your second code example) is almost guaranteed to become a problem eventually.

perhaps you'd be happier programming java

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays).