Sweetest Accessor?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm learning, so I'm trying different idioms. Perhaps in the end it
doesn't matter but I've been working on particularly terse idioms.

One particular demand is for object data accessor methods. There are a
lot of them and they all look somewhat alike -- sounds like a demand for
laziness. What's the shortest, "sweetest" accessor sub?

Here's what I've got (eg):


   sub name {
      my $obj        = shift;
      $obj->   = shift ||
This allows both gets and puts:

   $oldname = $obj->name;
   $obj->name ($newname);

It still doesn't satisfy me. The needless assignment-to-self irks. Note
that it does no good to change the order of precedence so that
$obj-> is returned (without assigning it) if shift tests false; by
then it's too late and shift has clobbered the old value. So here I test
shift within the right-hand side expression before making the

Here's another:


   sub name {
      $_[1] ? $_[0]-> =
      $_[1] : $_[0]->;

This avoids the needless assignment but now there's a second get of
$_[1]. Supposing that the object is more complex and that hitting the
object is more expensive than hitting the param, I'd guess this second
version is more efficient. Also, no assignment to a temp $obj. It looks
a bit odd to line break the statement after the assignment operator.

I realize that some oppose needlessly terse or obscure code but I'll ask
for forgiveness here. After all, an accessor method is simple. In the
end, it's a wash anyway; I'm just experimenting. I'll take comments on
either method shown and I'd love to see suggestions.
Xiong Changnian

Posted via a free Usenet account from http://www.teranews.com

Re: Sweetest Accessor?

On 03/27/2007 08:08 AM, Xiong Changnian wrote:
Quoted text here. Click to load it

perldoc perltoot
perldoc Class::Struct
perldoc Class::Accessor

Site Timeline