in reply to Constructing Context
Nice writeup. People keep getting confused by context and it's a fairly simple idea, even if their are a few edge cases that throw people off.
And while on the topic of context, if I keep responding to posts like this, people will think I'm planting shills in the audience :) Naturally, that means that what follows is a shameless plug for a module that makes dealing with context much easier (for subroutines).
Context is a great thing, but it trips up many people. It trips use people using other's code:
my $foo = some_func(); my ($foo) = some_func(); # may or may not behave the same!
It also trips up people writing code for others to use:
sub some_func { # do stuff return wantarray ? @results : \@results; # is void context OK? }
To solve this problem from the perspective of those writing code for others to use, I posted an RFC for Sub::Attributes. After some great feedback, I uploaded a module to the CPAN named Attribute::Context. It's easy to use. If you want to return an array, but return a reference in scalar context and warn about using it in void context, it used to be that you would have to write something like this:
sub some_func { # do stuff return wantarray ? @results : defined wantarray ? \@results : warn "Useless void context"; }
Not only is that ugly, it's also confusing and easy to write incorrectly. The if-else chain is hardly better:
sub some_func { # do stuff if (wantarray) { return @results; elsif (defined wantarray) { return \@results; else { warn "this is tedious"; } }
If you want all of your subroutines to have this behavior, it's going to get awfully tedious to code that every time. Now, you can just write this:
use Attribute::Context; sub some_func : Arrayref(WARNVOID) { # do stuff return @results; }
That's much easier to write, easier on the eyes, and is less likely to be buggy!
I also got rid of the nasty Iterator in exchange for a Custom attribute that returns an object in scalar context:
sub some_func : Custom(Some::Class) { # do stuff return @results; } # scalar context returns Some::Class->new(\@results)
I'll update the Custom attribute to be more flexible if people find it useful. There are also attributes for First (like CGI::param), Last and Count. More attributes may be added if requested.
Cheers,
Ovid
New address of my CGI Course.
|
|---|