|
Attribute::Property - Easy lvalue accessors with validation. |
Attribute::Property - Easy lvalue accessors with validation. ($foo->bar = 42)
package SomeClass;
use Attribute::Property;
use Carp;
sub new { bless { }, shift }
sub nondigits : Property { /^\D+\z/ }
sub digits : Property { /^\d+\z/ or croak "custom error message" }
sub anyvalue : Property;
sub another : Property;
sub value : Property {
my $self = shift; # Object is accessible as $_[0]
s/^\s+//; # New value can be altered through $_ or $_[1]
$_ <= $self->maximum or croak "Value exceeds maximum";
}
my $object = SomeClass->new;
$object->nondigits = "abc";
$object->digits = "123";
$object->anyvalue = "abc123\n";
$object->anyvalue('archaic style still works');
# These would croak
$object->nondigits = "987";
$object->digits = "xyz";
This module introduces the Property attribute, which turns your method into
an object property. The original code block is used only to validate new
values, the module croaks if it returns false.
Feel free to croak explicitly if you don't want the default error message.
Undefined subs (subs that have been declared but do not have a code block) with
the Property attribute will be properties without any validation.
In the validation code block, the object is in $_[0] and the value to be
validated is aliased as $_[1] and for regexing convenience as $_.
Your object must be a blessed hash reference. The property names will be used for the hash keys.
For class properties of C<Some::Module>, the hash C<%Some::Module> is used, for class properties of C<Module>, the hash C<%Attribute::Property::Module> is used.
In short: $foo->bar = 14 and $foo->bar(14) assign 14 to
$foo->{bar} after positive validation.
Old fashioned $object->property(VALUE) is still available.
This module requires a modern Perl, fossils like Perl 5.00x don't support our chicanery.
There is no license. This software was released into the public domain. Do with it what you want, but on your own risk. Both authors disclaim any responsibility.
Juerd Waalboer <juerd@cpan.org> <http://juerd.nl/>
Matthijs van Duin <pl@nubz.org>
|
Attribute::Property - Easy lvalue accessors with validation. |