That's untested, and not particularly beautiful. If you wanted to make it robust, keep around an array of valid keys for your class data. It's not guaranteed to handle nested references correctly, and it may fail in certain inheritance solutions.package Original; sub new { my $class = shift; my $other = shift; # hash ref, optional my $self = { name => 'the original', rating => 'supreme commander', boots => 'laced to the knee', }; if ($other) { foreach (keys %$other) { $self{$_} = $other->{$_}; } } bless($self, $class); return $self; } sub copy { my $self = shift; return $self->new($self); }
But it's an idea. perltootc has more interesting ideas.
If you're really interested in inheritance and smart defaults, separate initialization of the hash from the constructor:
And in a subclass:sub new { my $class = shift; my $self = _init(@_); # private method bless($self, $class); return $self; } sub _init { my %data = ( name => 'supreme commander two', rank => 'even better', toothbrush => 'purple with sparklies', ); if (@_) { foreach (keys %{ $_[0] }) { $data{$_} = ${$_[0]}->{$_}; # yuck, probably wrong } } return \%data; # reference! } sub copy { my $self = shift; return $self->new($self); # pass this as a hash ref }
Okay, now that's *officially* ugly. Just like a real OO language should be.sub copy { my $self = shift; my $new = __SUPER__->init($self->new($self)); return $new; }
In reply to Re: opinions on the best way to inherit class data
by chromatic
in thread opinions on the best way to inherit class data
by d_i_r_t_y
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |