My question concerns tied object classes. I would like to know if there is a way to prevent the DESTROY method from being called twice (once for the object, and once for the underlying hash that is tied) for objects such as the one I've created below. I know I can check "tied $this" within DESTROY, but this is truly a vile hack of a solution. Essentially what I would like to know is if there is a way to seperate the "magical" destructor for the tied object from the class destructor:
You may notice that this a wierd way of building a tied object. I don't know if this is common programming practice (specifically, the tie %{$this}, $class; line right within the object constructor), but it seems to work quite well. I build classes this way in order to allow access to an object's attributes through the object->{attribute} notation, while reserving the ability to mediate this access in the same way that attribute accessor/mutator methods would. Thus, I retain the straightforward hash-key object attribute syntax while also enjoying all the "object-oriented encapsulation" benefits of the the method call syntax.package SillyClass; require Tie::Hash; @ISA = (Tie::Hash); sub new { my $proto = shift; my $class = ref ($proto) || $proto; my $this = bless { }, $class; tie %{$this}, $class; return $this; } sub TIEHASH { my $self = shift; my $node = { color => 'blue', age => 12, pet => 'dog', }; return bless $node, $self; } sub DESTROY { my $self = shift; print "Calling DESTROY by $self\n"; } #------end class definition------ package main; my $fred = SillyClass->new(); undef $fred; ## DESTROY gets called twice, once by "$fred" and by + "tied $fred"
So I suppose I'm also asking another question: is there anything "wrong" about doing things in this way in the first place? Thanks very much for your help.
In reply to DESTROY for tied classes by MeowChow
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |