package Class::BuildMethods; use strict; use warnings; my %value_for; sub import { my $class = shift; my ($callpack) = caller(); while (@_) { my $method = shift; my $constraints; my $validation_sub; if ( 'HASH' eq ref $_[0] ) { $constraints = shift; if ( exists $constraints->{default} ) { $value_for{$callpack}{$method} = delete $constraints->{default}; } if ( exists $constraints->{validate} ) { $validation_sub = delete $constraints->{validate}; } if ( my @keys = keys %$constraints ) { require Carp; Carp::croak( "Unknown constraint keys (@keys) for ${callpack}::$method"); } } no strict 'refs'; if ($validation_sub) { *{"${callpack}::$method"} = sub { my $self = shift; return $value_for{$callpack}{$method} unless @_; my $new_value = shift; $self->$validation_sub($new_value); $value_for{$callpack}{$method} = $new_value; return $self; }; } else { *{"${callpack}::$method"} = sub { my $self = shift; return $value_for{$callpack}{$method} unless @_; $value_for{$callpack}{$method} = shift; return $self; }; } } } 1;