package Person;
{
my @attributes = (qw/NAME AGE/);
sub new
{
my $type = shift;
my $class = ref($type) || $type;
my %self = map { $_ => undef } @attributes;
my $access = sub
{
my ($name, $arg) = @_;
use Carp;
croak "Method '$name' unknown for class Person"
unless exists $self{$name};
$arg and $self{$name} = $arg;
$self{$name};
};
#### convenience methods are denined here...
for my $method ( keys %self )
{
no strict 'refs';
*$method = sub {
my $self = shift;
$access->( $method, @_ ); };
}
bless $access, $class;
return $access;
}
}
sub salute
{
my $self = shift;
print "Hello, I'm ",
$self->NAME,
" and I'm ",
$self->AGE, "!\n";
}
####
package main;
my $person = new Person;
# nice interface
$person->NAME( 'John Doe' );
$person->AGE( 23 );
$person->salute;
# this also works, of course
$person->('AGE', 24);
$person->salute;
# this doesn't
$person->('TOES', 12);
##
##
Hello, I'm John Doe and I'm 23!
Hello, I'm John Doe and I'm 24!
Method 'TOES' unknown for class Person at Person.pl line 59