Your inside-out implementation is missing the obligatory destructor.
sub DESTROY { my $id = refaddr shift; delete $_->{ $id} for \ ( %street, %city, %state, %zip); }

I'd like to contrast an implementation of the Address class based on the Alter module. It is itself hash-based and thus closer to the original hash-based implementation than the inside-out variant, while still offering the black-box-inheritance properties. Essentially, the changes are that the ego() function is called on the object before each access to the object data.

#class Address (Alter-based) package Address; use strict; use warnings; use Alter ego => {}; # alter ego is a hash #constructor sub new { my ($class) = @_; my $self = \ my $o; # the object proper (a scalar ref) %{ ego $self } = ( # set up the ego for this class _street => undef, _city => undef, _state => undef, _zip => undef ); bless $self, $class; return $self; } sub street { my ( $self, $street ) = @_; ego( $self)->{_street} = $street if defined($street); return ego( $self)->{_street}; } sub city { my ( $self, $city ) = @_; ego( $self)->{_city} = $city if defined($city); return ego( $self)->{_city}; } sub state { my ( $self, $state ) = @_; ego( $self)->{_state} = $state if defined($state); return ego( $self)->{_state}; } sub zip { my ( $self, $zip ) = @_; ego( $self)->{_zip} = $zip if defined($zip); return ego( $self)->{_zip}; } sub print { print "Address: $_->{_street}\n". "$_->{_city}\n" . "$_->{_state}\n" . "$_->{_zip}\n\n" for ego shift; } 1;
Anno

In reply to Re^3: object oriented tutorial question by Anno
in thread object oriented tutorial question by convenientstore

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.