Learning Perl Objects, References amp;amp; Modules [Electronic resources]

Randal L. Schwartz

نسخه متنی -صفحه : 199/ 81
نمايش فراداده

8.7 Starting the Search from a Different Place

A better solution is to tell Perl to search from a different place in the inheritance chain:

{ package Animal;
sub speak {
my $class = shift;
print "a $class goes ", $class->sound, "!\n";
}
}
{ package Mouse;
@ISA = qw(Animal);
sub sound { "squeak" }
sub speak {
my $class = shift;
$class->Animal::speak(@_);
print "[but you can barely hear it!]\n";
}
}

Ahh. As ugly as this is, it works. Using this syntax, start with Animal to find speak and use all of Animal's inheritance chain if not found immediately. The first parameter is $class (because you're using an arrow again), so the found speak method gets Mouse as its first entry and eventually works its way back to Mouse::sound for the details.

This isn't the best solution, however. You still have to keep the @ISA and the initial search package in sync (changes in one must be considered for changes in the other). Worse, if Mouse had multiple entries in @ISA, you wouldn't necessarily know which one had actually defined speak.

So, is there an even better way?