There's a nifty module on CPAN which ensures that object attributes can only be retrieved and altered inside the objects' class: Alter by Anno. Sample:

package Foo; use Alter ego => {}; my @attr = qw ( bar quux ); sub new { my $class = shift; my $obj = {}; bless $obj, $class; if ( @_) { @_ % 2 and die "odd number of arguments, aborted"; my %args = @_; my %params; for (@attr) { $params{ $_} = delete $args{ $_}; } warn "unknown key $_!\n" for keys %args; for ( keys %params) { $obj->$_( $params{ $_}); } } return $obj; } sub bar { my $obj = shift; ego( $obj)->{ bar} = shift if @_; return ego( $obj)->{ bar}; } sub quux { my $obj = shift; ego( $obj)->{ quux} = shift if @_; ego( $obj)->{ quux}; } package main; print "\nOutput:\n" my $foo = Foo->new( foo => 1, bar => 2, quux => 3); print "\$foo reference is '$foo'\n"; $foo->{bar} = "something"; # hash lookup $foo->bar(5); # method print "method: \$foo->bar( ) = ", $foo->bar( ), "\n"; print "hash: \$foo->{ bar} = ", $foo->{ bar}, "\n"; __END__ Output: unknown key foo! $foo reference is 'Foo=HASH(0x8a007a4)' method: $foo->bar( ) = 5 hash: $foo->{ bar} = something

Here, a Foo object is just a blessed hash reference. Outside its class it behaves just as a normal hash reference. Its Foo attributes can be retrieved or set only via methods.

Note that the attribute container doesn't need to be of the same type as the object. The object could be a scalar reference (or an anonymous subroutine) and still have a hash magically attached.


In reply to Re: Prevent direct acces to object's attributes by shmem
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.