What about a copy constructor? Something like the following might even be inheritable, or set class-based defaults:
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); }
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.

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:

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 }
And in a subclass:
sub copy { my $self = shift; my $new = __SUPER__->init($self->new($self)); return $new; }
Okay, now that's *officially* ugly. Just like a real OO language should be.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.