Two months ago, I mentioned Contextual::Return and showed how to use it to create a dual variable:
use Contextual::Return;my $result = NUM { 13 } STR { "Permission Denied" };if ($result == 13) { ... } # trueif ($result =~ /denied/i) { ... } # also true!
Such a result is fascinating to me. First, I had not put together all the pieces of how this kind of a value was possible using relatively straightforward Perl. Second, the syntax for specifying the behavior is rather remarkable at first glance, and yet understandable once I spent a bit of time pawing through the code. But before we drill down into the implementation, let’s back up a minute, and look at the kinds of problems that Contextual::Return intends to solve.
Many built-in Perl functions have related-but-distinct return values when invoked in either a scalar context or a list context. For example, the grep function returns a count of successful items in a scalar context, but the items themselves in a list context. Similarly, localtime returns a time string in a scalar context, or the elements that make up the time in a list context.
You can write Perl subroutines that emulate this behavior by paying attention to wantarray (which really should be called “wantlist”):
sub my_funky_func { … return @some_list if wantarray; # list context return $some_scalar if defined wantarray and not wantarray; # scalar context ## "not defined...
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: