http://www.perlmonks.org?node_id=65201


in reply to How can I create private object variables?

Use closures. Check out perltoot for more info on how this code works.

{ package Foo; sub new { my $pkg = shift; my %data = ( bar => undef, ); bless sub { my $field = shift; @_ and $data{$field} = shift; $data{$field} }, $pkg } sub bar { my $self = shift; # the blessed closure $self->( 'bar', @_ ) } }
And use:
my $foo = new Foo; $foo->bar(42); # set it print $foo->bar; # get it