<?xml version="1.0" encoding="windows-1252"?>
<node id="222941" title="$foo-&gt;bar = 14;" created="2002-12-29 14:25:51" updated="2005-08-13 22:58:03">
<type id="120">
perlmeditation</type>
<author id="132236">
Juerd</author>
<data>
<field name="doctext">
&lt;p&gt;
Traditionally, object properties in Perl are retrieved and set either through methods or by using the object as the reference it is.
&lt;/p&gt;
&lt;p&gt;
To automate the creation of accessor methods, I don't use a module, but a simple closure creating loop like this one:
&lt;code&gt;
BEGIN {
    no strict 'refs';
    for my $property (qw/id debug display_time default_text/) {
        *$property = sub {
            my ($self, $value) = @_;
            croak "Too many arguments for $property method" if @_ &gt; 2;
            $self-&gt;{$property} = $value if @_ == 2;
            return $self-&gt;{$property};
        }
    }
}
&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
In #perlhelp (efnet), xmath pointed out that methods can be used as lvalues (with the lvalue attribute). It appears attributes work on anonymous subs. That knowledge combined leads to something like:
&lt;code&gt;
BEGIN {
    no strict 'refs';
    for my $property (qw/id debug display_time default_text/) {
        *$property = sub : lvalue { $_[0]-&gt;{$property} };
    }
}
&lt;/code&gt;
&lt;/p&gt;
So that means:
&lt;code&gt;
OLD SITUATION           NEW SITUATION

$foo-&gt;bar;              $foo-&gt;bar;
$foo-&gt;bar(15);          $foo-&gt;bar = 15;
{
  my $temp = $foo-&gt;bar;
  $temp =~ s/foo/bar/;
  $foo-&gt;bar($temp);
}                       $foo-&gt;bar =~ s/foo/bar/
&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Before I'm going to change my coding style, I'd like to know what the community thinks of it. The lvalue attribute is experimental.
&lt;/p&gt;
&lt;p&gt;
Note that I know this doesn't check the new values. Neither did my old code - I don't really care :) And no, I don't like using the hash reference for my external API.
&lt;/p&gt;
&lt;p&gt;
So, what do you think?
&lt;/p&gt;
&lt;p&gt;&lt;font color=green&gt;&lt;pre&gt;
- Yes, I &lt;a href="http://plp.juerd.nl/" target="_blank"&gt;&lt;font color="green"&gt;reinvent&lt;/font&gt;&lt;/a&gt; wheels.
- Spam: Visit &lt;a href="http://eurotraq.com/" target="_blank"&gt;&lt;font color="green"&gt;eurotraQ&lt;/font&gt;&lt;/a&gt;.
&lt;/pre&gt;&lt;/font&gt;&lt;/p&gt;</field>
</data>
</node>
