in reply to Prevent direct acces to object's attributes
And here is the user code:package MyMod; use strict; use warnings; use Carp; use Scalar::Util qw(refaddr); # Have a private hash for each attribute my %atr1; # Attribute 1 my %atr2; # Attribute 2 # etc. # This hash is used by the general purpose accessors my %hashrefs = ( atr1 => \%atr1, atr2 => \%atr2, #etc ); sub new { my $class = shift; my %args = @_; # create some unique number from a reference my $self = \do{my $dummy}; my $key = refaddr($self); $atr1{$key} = $args{'atr1'}; $atr2{$key} = $args{'atr2'}; # more attributes... bless($self, $class); # ... some code to populate attribs from passed parms return $self; } # General purpose get/set sub set { my ($self, $attr, $value) = @_; my $key = refaddr $self; if (exists $hashrefs{$attr} ) { $hashrefs{$attr}{$key} = $value } else { carp "Invalid attribute name $attr" } } sub get { my ($self, $attr) = @_; my $key = refaddr $self; if (exists $hashrefs{$attr} ) { return $hashrefs{$attr}{$key} } else { carp "Invalid attribute name $attr"; return; } } # MUST have a destructor sub DESTROY { my ($self) = @_; my $key = refaddr $self; delete $atr1{$key}; delete $atr2{$key}; # likewise for other attribute hashes } 1;
use strict; use warnings; use MyMod; my $mm = MyMod->new(atr1 => 1, atr2 => 'string2'); print $mm->get('atr1')."\n"; print $mm->get('atr2')."\n"; $mm->set('atr1', 42); print $mm->get('atr1')."\n"; $mm->{atr1} = 3000; <<<<---- Fails "Not a HASH reference"
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Prevent direct acces to object's attributes
by JavaFan (Canon) on Sep 08, 2009 at 10:11 UTC |