8.1. If We Could Talk to the Animals...
Obviously, the castaways can't survive on coconuts
and pineapples alone. Luckily for them, a barge carrying random farm
animals crashed on the island not long after they arrived, and the
castaways began farming and raising animals.
Let's let those animals talk for a moment:
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;
This results in:
a Cow goes moooo!
a Horse goes neigh!
a Sheep goes baaaah!
Nothing spectacular here: simple subroutines, albeit from separate
packages, and called using the full package name.
Let's create an entire pasture:
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"}; # Symbolic coderef
}
This results in:
a Cow goes moooo!
a Cow goes moooo!
a Horse goes neigh!
a Sheep goes baaaah!
a Sheep goes baaaah!