Update: the package now defines attributes for First, Last, and Count, has 36 tests and updated POD. The link below has been updated to point to the new package.
In this node, I mentioned an idea I had about altering a subroutine's behavior using attributes to make it easy to understand what is intended. Rather than put together a full package, I've created a small test package that defines just two attributes "Arrayref" and "Iterator". If called in scalar context, it returns a reference to an array. Otherwise, it returns the array. An alternate "NOVOID" parameter may be specified to make calling it in void context fatal.
The benefit is an easy to use/understand module that simplifies many subroutine context behaviors without forcing us to continually rewrite them. There's a bit of POD and some tests to show what's going on. Below is a sample of how you might use it:
use base 'Sub::Attributes'; sub reverse_me : Arrayref(NOVOID) { # calling in void context is now f +atal return reverse @_; } my @list = reverse_me(1,2,3); # (3,2,1) my $list = reverse_me(1,2,3); # [3,2,1] sub do_stuff : Iterator { # calling in void context is legal, but a no +-op return @_; } my @list = do_stuff(1,2,3); # simply returns the list my $list = do_stuff(1,2,3); # iterator object print $iterator->next; # prints 1 print $iterator->next; # prints 2 print $iterator->next; # prints 3 print $iterator->prev; # prints 3 print $iterator->prev; # prints 2 print $iterator->prev; # prints 1
Personally, I don't know that the iterator object is useful. It doesn't delay creation of the list and undefined (or false) items in the list can break things like while (defined $result->next). If you can convince me why I should keep it, I will. It's just there for demo purposes.
Suggestions, code reviews, or general rants appreciated.
Cheers,
Ovid
New address of my CGI Course.
|
|---|