In my opinion, you lose some expressiveness by going entirely to tied objects. If your objects are more than just structs, you will have some method calls like this:
my $ret = $obj->do_something($with, $these, $args);
The only (sane) way to do this with the tied approach is using tied(%h), which I think is really ugly.
One thing you might consider (which I've never tried) is to overload the hashref operator for your objects. The perldoc for overload has some examples about overloading these referencing operators. Something like this:
package Widget;
use overload '%{}' => sub {
my $self = shift;
tie my %h, __PACKAGE__, $self;
\%h;
};
Create a hash tie'd into the same package, that has an associated object. Then have FETCH (and STORE if you like) just translate into the appropriate method calls on that object, of course ignoring keys that aren't for just getter/setter methods. Then you could interpolate like this:
my $widg = Widget->new;
print "$widg->{name} is the same as " . $widg->name;
Note that this will work even if you don't implement your class using blessed hashrefs. And you still can protect the object's internals from direct access..
Update: Now that I think of it, could TIEHASH in this class be implemented like this (i.e, the tied hash is the object it it corresponds to)?
sub TIEHASH {
my ($pkg, $object) = @_;
return $object;
}
sub FETCH {
my ($self, $key) = @_;
$self->$key;
}
Like I said, I've never tried this so I could be missing something, but it sounds like fun. ;)
Update 2: It's almost a day later and I just thought of something. If anyone is coming to this thread late, I just want to warn you that your '%{}' overload needs to still allow for the class methods to get to the "real" internal data structure (only if your real structure is a hashref of course)! You will probably have to have to use caller to sort out which times the hashref overload must actually return the real object.
|