in reply to Ironclad protection of instance data
package My::Class; use strict; use warnings; { # hide from the rest of the class my %CLASSDATA = ( foo => 1, bar => 2, baz => 3 ); # install generic accessor/mutator methods no strict 'refs'; for my $key(keys %CLASSDATA) { *$key = sub { shift; $CLASSDATA{$key} = shift if @_; return $CLASSDATA{$key}; }; } } my @ATTRIBUTES = qw/name alias race/; sub new { my ($class, %args) = @_; my %data = (name => 'aragorn', alias => 'elessar', race => 'man', +%args); my $self = sub { my $field = shift; if(@_) { $data{$field} = shift } return $data{$field}; }; bless $self, $class; } for my $attr (@ATTRIBUTES) { no strict 'refs'; *$attr = sub { my $self = shift; return $self->($attr, @_); }; }
|
|---|