x
Loading
 Loading
Hello, Guest | Login | Register

Many Happy Returns

Randal Schwartz explains why you should consider Contextual::Return for your next tricky return value problem.

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) { ... } # true if ($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:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Got Security? You're in Denial
  2. KDE 4.4: Does It Work Yet?
  3. Writing Custom Nagios Plugins with Python
  4. Power Up Linux GUI Apps
  5. Tweeting from the Command Line with Twyt
Follow Linux Magazine
Rackspace