Traditionally, object properties in Perl are retrieved and set either through methods or by using the object as the reference it is.
To automate the creation of accessor methods, I don't use a module, but a simple closure creating loop like this one:
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 @_ > 2;
$self->{$property} = $value if @_ == 2;
return $self->{$property};
}
}
}
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:
BEGIN {
no strict 'refs';
for my $property (qw/id debug display_time default_text/) {
*$property = sub : lvalue { $_[0]->{$property} };
}
}
So that means:
OLD SITUATION NEW SITUATION
$foo->bar; $foo->bar;
$foo->bar(15); $foo->bar = 15;
{
my $temp = $foo->bar;
$temp =~ s/foo/bar/;
$foo->bar($temp);
} $foo->bar =~ s/foo/bar/
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.
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.
So, what do you think?
- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.