http://www.perlmonks.org?node_id=412628


in reply to Use method/function signatures with Perl

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.

Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }