Here is your module implemented as an inside-out class:
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;
And here is the user code:
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"

In reply to Re: Prevent direct acces to object's attributes by cdarke
in thread Prevent direct acces to object's attributes by vitoco

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.