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

Been using perl on and off for a while but on a rainy afternoon started looking at OO. Normally with I can figure out all problems by reading other people's posts but I don't seem to be getting anywhere with this one, despite it being REALLY BASIC! Your forgiveness in advance is required.
#!/usr/bin/perl use strict; Cow->speak; { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } } { package Cow; our @ISA = qw(Animal); sub sound { "moooo" } }
I copied this directly from http://perldoc.perl.org/perlboot.html. When I run it I get
Can't locate object method "speak" via package "Cow" at ./testOO1.pl line 6.
In fact I can't seem to get inheritance to work at all. What extremely silly thing am I (not) doing? Thanks

Replies are listed 'Best First'.
Re: really simple OO inheritance question
by jdporter (Paladin) on Jun 27, 2010 at 12:15 UTC

    You're calling the method before all the class initialization is complete. Normally I'd put all the class definitions before any "executable code". It turns out, only one statement in your code above is not getting executed in time for your Cow->speak call, and that's the

    our @ISA = qw(Animal);
    statement. That is (unfortunately) "normal" code, not definitional. You can make it happen earlier by putting it in a begin block:
    BEGIN { our @ISA = qw(Animal); }
    but it's considered better practice (by some, anyway) to use a real pragmatic statement to define your inheritance relations:
    use base 'Animal';

    What is the sound of Windows? Is it not the sound of a wall upon which people have smashed their heads... all the way through?

      Ah yes, it works now!

      That'll teach me for treating classes as subroutines... Looks like I've some way to go.

      Thanks greatly for putting me out of my misery!

Re: really simple OO inheritance question
by moritz (Cardinal) on Jun 27, 2010 at 12:07 UTC

    It works if you put the Cow->speak below the class definitions.

    The reason is that the assignment to @ISA happens at run time, so Cow only inherits from Animal for code that comes after the package/class definition.

    Perl 6 - links to (nearly) everything that is Perl 6.