Play with it:
#!/usr/bin/perl
use warnings;
use strict;
package Class::GetSet;
sub new { my $class = shift; return bless({@_}, $class) }
sub __set { $_[0]->{ $_[1] } = $_[2] }
sub __get { return $_[0]->{ $_[1] } }
use vars qw($AUTOLOAD);
sub AUTOLOAD
{
no strict 'refs';
if ($AUTOLOAD =~ /^.*::(\w+)$/o && exists $_[0]->__has->{$1}->{'rea
+d'} ) {
my $attr = $1;
*{$AUTOLOAD} = sub { my $s = shift; return ($s->__get(
+$attr, @_)) };
goto &$AUTOLOAD;
} elsif ($AUTOLOAD =~ /^.*::set_(\w+)$/o && exists $_[0]->__ha
+s->{$1}->{'write'} ) {
my $attr = $1;
*{$AUTOLOAD} = sub { my $s = shift; return ($s->__set(
+$attr, @_)) };
goto &$AUTOLOAD;
}
# subs like DESTROY
return if $AUTOLOAD =~ /^.*::[A-Z]+$/;
die "Unimplemented $AUTOLOAD";
}
+
+
package Dummy;
+
+
use base qw(Class::GetSet);
sub __has { return { foo => { read => 1, write => 1 }, bar => { read =
+> 1 } } }
+
+
package main;
+
+
my $d = Dummy->new( foo => 1, bar => 2);
print "foo = '". $d->foo ."'\n";
$d->set_foo( 'xxx' );
print "foo = '". $d->foo ."'\n";
+
+
print "bar = '". $d->bar ."'\n";
$d->set_boo( 'xxx' );
Example above is for example of using the closures for dynamic generation of methods.