Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Tie::SecureHash and AUTOLOAD'ing

by TheDamian (Priest)
on Apr 10, 2003 at 22:12 UTC ( #249756=note: print w/ replies, xml ) Need Help??


in reply to Tie::SecureHash and AUTOLOAD'ing

AUTOLOAD works fine with Tie::Securehash. Like this...

use Tie::SecureHash; package DogTag; sub new { my ($class, %args) = @_; Tie::SecureHash->new( $class, __name => $args{name}, __rank => $args{rank}, __serial => $args{serial} ); } sub report { my ($self) = @_; print $self->name, "\n"; print $self->rank, "\n"; print $self->serial, "\n"; } sub DESTROY {} # Usually needed when using AUTOLOAD sub AUTOLOAD { my ($self) = @_; $AUTOLOAD =~ s/.*::/__/; return $self->{$AUTOLOAD}; } package main; my $id = DogTag->new(name=>"Smith", rank=>"private", serial=>1234567); $id->report();


Comment on Re: Tie::SecureHash and AUTOLOAD'ing
Download Code
Re: Re: Tie::SecureHash and AUTOLOAD'ing
by forkboy (Sexton) on Apr 11, 2003 at 02:21 UTC
    arh yes, but I can also do this
    package main; my $id = DogTag->new(name=>"Smith",rank=>"private",serial=>'1234567'); print $id->name();
    which somewhat defeats the purpose of Tie::SecureHash. What I really need is an autoloader that correctly enforces the same rules as Tie::SecureHash
      Okay, but first notice that the AUTOLOAD is enforcing encapsulation. You can call attribute accessors, but only ever to retrieve the current values, not to set new ones.

      Remember: encapsulation is not about preventing access to attributes; it's about controlling access to attributes.

      If you want the control that the AUTOLOAD enforces to be identical to the control that Tie::SecureHash enforces (which is a perfectly reasonable thing to want), just code AUTOLOAD accordingly:

      sub AUTOLOAD { my ($self, $newval) = @_; $AUTOLOAD =~ s/.*:://; my $attr; if (exists $self->{$attr=$AUTOLOAD}) { # public attribute always accessible } elsif (exists $self->{$attr="_$AUTOLOAD"}) { croak "Cannot access protected attribute '$attr'" unless caller().isa(ref $self); } elsif (exists $self->{$attr="__$AUTOLOAD"}) { croak "Cannot access private attribute '$attr'" unless caller() eq ref $self; } else { croak "No such attribute ($AUTOLOAD) for object" } $self->{$attr} = $newval if @_ > 1; return $self->{$attr}; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://249756]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2015-07-04 21:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls