$tv_horse->set_color( $eating->set_color( color_from_user( ) ));
The implementation given earlier returns the newly updated value.
Frequently, this is the easiest code to write, and often the fastest
to execute.
If you return the previous parameter, you can easily create
"set this value temporarily to
that" functions:
{
my $old_color = $tv_horse->set_color("orange");
... do things with $tv_horse ...
$tv_horse->set_color($old_color);
}
This is implemented as:
sub set_color {
my $self = shift;
my $old = $self->{Color};
$self->{Color} = shift;
$old;
}
sub set_color {
my $self = shift;
if (defined wantarray) {
# this method call is not in void context, so
# the return value matters
my $old = $self->{Color};
$self->{Color} = shift;
$old;
} else {
# this method call is in void context
$self->{Color} = shift;
}
}
If you return the object itself, you can chain settings:
my $tv_horse =
Horse->named("Mr. Ed")
->set_color("grey")
->set_age(4)
->set_height("17 hands");
This works because the output of each setter is the original object,
becoming the object for the next method call. Implementing this is
again relatively easy:
sub set_color {
my $self = shift;
$self->{Color} = shift;
$self;
}