in reply to tie for Perlish, encapsulated objects
This just seems like a fancy wrapper to $instance->{attribute} notation. Yeah, you can make assignments to more complicated things, but you can do that with overload as well. I guess I just don't get it.
I've fallen in the habit of implementing this type of thing for set and get operations:
package SomePackage; use base 'Class::Base'; ## super-simple 'new' sub new { my $self = shift; bless { one => 1, two => 2 }, $self; } sub set { my $self = shift; my $attrib = shift; return $self->error("No such attribute '$attrib'") unless exists $self->{$attrib} my $value = shift; # check to make sure we're setting the same kind of reference, if i +t matters if (ref $self->{$attrib} && ref $value ne ref $self->{$attrib}) { return $self->error("Reference types do not match for '$attrib' +set.") } $self->{$attrib} = $value; return 1; # true on success } sub get { my ($self, $attrib) = @_; return $self->error("Attribute '$attrib' doesn't exist") unless exists $self->{$attrib}; my $value = $self->{$attrib}; return $value; } 1;
This means I can do $instance->set('one', 'Hey there!'); and $instance->get('two');. If certain attributes have special rules to validate data, I can deal with those by altering 'set' slightly. For example:
# set from above gets renamed _set_DEFAULT sub set { my ($self, $attrib, $value) = @_; if ( $self->can('_set_'.$attrib) ) { my $result; eval "\$result = \$self->_set_$attrib($value)"; return $result; } else { return $self->_set_DEFAULT($attrib, $value); } }
Something like that is much cleaner and clearer in the implmentation. I like the idea that when I see $instance->{attrib} = 2, I know the code is messing about with something advanced, while $instance->set('attrib', 2) is playing by the rules.
Besides, with Perl6's advancements in lvalue subs, it will be possible to do something like $instance->accessor('attrib') = 2, and we both win, so I don't see much point in debating the tie methodology.
|
|---|