sub Cow::speak {
print "a Cow goes moooo!\n";
}
sub Horse::speak {
print "a Horse goes neigh!\n";
}
sub Sheep::speak {
print "a Sheep goes baaaah!\n";
}
Cow->speak;
Horse->speak;
Sheep->speak;
And once again, this results in:
a Cow goes moooo!
a Horse goes neigh!
a Sheep goes baaaah!
That's not fun yet. You've got the
same number of characters, all constant, no variables. However, the
parts are separable now:
my $beast = "Cow";
$beast->speak; # invokes Cow->speak
Take the arrow invocation and put it back in the barnyard example:
sub Cow::speak {
print "a Cow goes moooo!\n";
}
sub Horse::speak {
print "a Horse goes neigh!\n";
}
sub Sheep::speak {
print "a Sheep goes baaaah!\n";
}
my @pasture = qw(Cow Cow Horse Sheep Sheep);
foreach my $beast (@pasture) {
$beast->speak;
}
There! Now all the animals are talking, and safely at that, without
the use of symbolic coderefs.
But look at all that common code. Each speak
routine has a similar structure: a print operator
and a string that contains common text, except for two words. One of
OOP's core features minimizes common code: if you
write it only once, you'll save time. If you test
and debug it only once, you'll save more time.