Perl300 has asked for the wisdom of the Perl Monks concerning the following question:
I am going through book "Intermediate Perl" and started with Object Oriented section. I have created a distribution Animal and inside it:
bin/pasture
use Animal; use Cow; use Horse; use Sheep; Cow->speak; Horse->speak; Sheep->speak;
lib/Animal.pm
package Animal; use 5.006; use strict; use warnings; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } sub sound { die "'You have to define sound() in a subclass' found"; }
lib/Cow.pm
package Cow; use 5.006; use strict; use warnings; use Animal; our @ISA = qw(Animal); sub sound { "moooo" }
lib/Sheep.pm
package Sheep; use 5.006; use strict; use warnings; use Animal; our @ISA = qw(Animal); sub sound { "baaaah" }
lib/Horse.pm
package Horse; use 5.006; use strict; use warnings; use Animal; our @ISA = qw(Animal); sub sound { "neigh" }
When I run ~/localperl/bin/perl -Ilib bin/pasture I get following output:
a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah!
As per book, explanation of this behavior is:
What happens when we invoke Cow−>speak now?
First, Perl constructs the argument list. Here, it’s just Cow. Then Perl looks for Cow::speak. That’s not there, so Perl checks for the inheritance array @Cow::ISA. It finds @Cow::ISA contains the single name Animal.
Perl next looks for speak inside Animal instead, as in Animal::speak. That found, Perl invokes that method with the already frozen argument list, as if we had said:
Animal::speak('Cow'); #This is the part I am having trouble understanding. How did "Cow" become an argument when I didn't specify it anywhere?As I mentioned in comment, I am unable to understand: How did "Cow" become an argument when I didn't specify it anywhere?
Can someone please help me understand this behavior? (Forgive me for the long post.)
|
---|