You have a classic example of polymorphism. TMTOWTDI, here is one. In the loop we change the names of the animals to be blessed references of the relevant class. The trick here is that the second argument to
bless is the class name, which can be a text string (otherwise we are into nasty
evals).
use warnings;
use strict;
package Cow;
{
sub speak {
print "Moo\n"
}
}
package Horse;
{
sub speak {
print "Hi, my name is Ed\n"
}
}
package Sheep;
{
sub speak {
print "Baaaah\n"
}
}
my @pasture = qw(Cow Cow Horse Sheep Sheep);
foreach my $animal (@pasture) {
$animal = (bless \do{my $anon}, $animal);
$animal->speak();
}
Produces:
Moo
Moo
Hi, my name is Ed
Baaaah
Baaaah