But was there anything specific to C<Horse> in that method? No. Therefore,
it's also the same recipe for building anything else that inherited from
-C<Animal>, so let's put it there:
+C<Animal>, so let's put C<name> and C<named> there:
{ package Animal;
sub speak {
sub name {
my $either = shift;
- ref $either
- ? $$either # it's an instance, return name
- : "an unnamed $either"; # it's a class, return generic
+ ref $either ? $$either : "Any $either";
}
Here, the C<?:> operator comes in handy to select either the
holder to C<$either> to show that this is intended:
my $horse = Horse->named("Mr. Ed");
- print Horse->name, "\n"; # prints "an unnamed Horse\n"
+ print Horse->name, "\n"; # prints "Any Horse\n"
print $horse->name, "\n"; # prints "Mr Ed.\n"
and now we'll fix C<speak> to use this:
}
sub name {
my $either = shift;
- ref $either
- ? $$either # it's an instance, return name
- : "an unnamed $either"; # it's a class, return generic
+ ref $either ? $$either : "Any $either";
}
sub speak {
my $either = shift;
which prints:
Mr. Ed eats hay.
- an unnamed Sheep eats grass.
+ Any Sheep eats grass.
An instance method with parameters gets invoked with the instance,
and then the list of parameters. So that first invocation is like:
## in Animal
sub name {
my $either = shift;
- ref $either ?
- $either->{Name} :
- "an unnamed $either";
+ ref $either ? $either->{Name} : "Any $either";
}
And of course C<named> still builds a scalar sheep, so let's fix that