sub name {
my $self = shift;
if (1 == @_ && ! ref $_[0]) {
$self->{name} = shift;
return $self;
}
elsif (! @_) {
return $self->{name};
}
else {
croak "Unknown arguments to name()";
}
}
There is a lot of readability to be gained by just writing it differently:
sub name {
my $self = shift;
$self->{name} = shift, return $self if @_ == 1
croak "Unknown arguments to name" if @_;
return $self->{name};
}
Of course, because I hate methods that return $self (and methods that return something different based on the number of arguments), I would just have this instead:
sub name {
my $self = shift;
$self->{name} = shift if @_ == 1
croak "Unknown arguments to name" if @_;
return $self->{name};
}
which again is easier to read and type. But this is still based on your example. For those who don't mind having the return value being consistent regardless of the number of arguments, there is an even better way to write the accessor, but then the similarity with your example is gone:
sub name {
@_ > 1 and croak "Too many arguments for name";
my $self = shift;
return @_ ? $self->{name} = shift : $self->{name};
}
(Note that I changed the error message to something that looks like what perl itself uses in such a situation.)
But nothing beats:
sub name : lvalue { shift->{name} }
in writing, reading and maintaining the method, but also in writing, reading and maintaining the code that uses it.
-
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.