nysus has asked for the wisdom of the Perl Monks concerning the following question:

I'm going through merlyn's OO tuturial. I'm getting a Can't locate object method "speak" via package "Cow" error on the following bit of code:
#!/usr/bin/perl my @pasture; my $animal; @pasture = qw(Cow Cow Horse Sheep Sheep Cow); foreach $animal (@pasture) { $animal->speak; } { package Cow; @ISA = qw(Animal); sub sound { "moooo" } } { package Horse; sub sound { "neigh" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } } { package Sheep; sub sound { "baaaaaaaa" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } } { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } }

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar";
$nysus = $PM . $MCF;

Replies are listed 'Best First'.
(tye)Re: @ISA doesn't seem to work
by tye (Sage) on Jun 05, 2001 at 16:31 UTC

    The order you would be executing the code is, in part, as follows:

    • $animal gets set to "Cow".
    • You ask "Cow" to speak.
    • ...
    • You make a "Cow" an "Animal".
    • ...
    At the time when you ask the "Cow" to speak(), the "Cow" isn't an "Animal" yet.

    Either move your test code to the bottom of the file or initialize @ISA inside of a BEGIN block.

            - tye (but my friends call me "Tye")