I just chanced upon Simplified attribute accessors using overloading. It's a reinvention of the common Perl 5 idiom of having a single method for accessing and mutating an objects state.

$value = $object->field_name; # get value $object->field_name($value); # set value

in Python!

def givenName(self, value=omitted): if value is not omitted: self._givenName=value return self._givenName

In Perl5 you would do it something like this:

sub givenName { my $self = shift; $self->{_givenName} = shift if @_; return $self->{_givenName}; };

In Perl 6 (assuming I've managed to remember all that Exegesis and Apocalypse stuff) you could do it with multi-methods something like this:

multi method givenName (Foo $self) { $self._givenName; }; multi method givenName (Foo $self, $value) { $self._givenName = $value; };

Which is nice, since we completely separate the accessor / mutator code. Alternatively if you want it all wrapped up in a single subroutine you could use an optional argument:

method givenName ( ?$value ) { defined $value ? $._given_name = $value : $._given_name; };

(is it possible to tell the difference between an optional value that isn't supplied and an optional value passed as undef in Perl 6?)

I know some people dislike the idiom and prefer the extra clarity of separate accessor/mutator method names - but I still think this is cute ;-)


In reply to Single accessor/mutator idiom in Perl5, Perl6 and Python by adrianh

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.