Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
HACK Return Smarter Values #92 This technique even works with classes and objects; you don't have to export your methods for Fatal to work. H A C K Return Smarter Values Choose the correct scalar for any context. Hack #92 #92 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, bool- ean, 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-undocu- menting infrastructure: if (wantarray) { return @some_list; } elsif (defined wantarray) { return $some_scalar; } else { do_something( ); return; } # wantarray true --> list context # wantarray defined --> scalar context # wantarray undefined --> void context 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. Chapter 9, Expand Your Perl Foo | 235