Hack #92. Return Smarter Values

Choose the correct scalar for any context.

There's always one troublemaker in any bunch. When it comes to return contexts, that troublemaker is scalar.

List and void contexts are easy. In list context you just return everything. In void context, return nothing. Scalar contexts allow you to return only one thing, but there are just too many alternatives: a string, a count, a boolean value, a reference, a typeglob, or an object.

The real problem, though, isn't actually that there are too many types of possible return value in scalar context; the real problem is that Perl simply doesn't provide you with enough...well...context with which to decide. The only basis you have for knowing whether to return a string, number, boolean, and so on, is receiving a single uninformative defined-but-false value from wantarray.

Even then, using wantarray leads to a lot of unnecessary and self-undocumenting infrastructure:

if (wantarray)                # wantarray true      --> list context
{
    return @some_list;
}
elsif (defined wantarray)     # wantarray defined   --> scalar context
{
    return $some_scalar;
}
else                          # wantarray undefined --> void context
{
    do_something( );
    return;
}

It would be much easier if you could just specify a single return statement that knew what to return in different contexts, perhaps:

return
    LIST   { @some_list     }
    SCALAR { $some_scalar   }
    VOID   { do_something( ) };

That's exactly what the Contextual::Return CPAN module does. It makes the previous example work like you'd expect. ...

Get Perl Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.