Hello All,

Just started learning OOPs in Perl from the book 'Intermediate Perl' written
by Randal.

I have written a small program given below. Its working at most places
except while printing color of unnamed creatures. Just execute the script
and you will figure out the bug. Could someone explain where am I going
wrong in the following script. (I know I have not used strict pragmas. :) )

TIA

Cheers,
Parag

#!/usr/bin/perl
####################
#Author: Parag Kalra
####################
{ package Animal;
    sub speak {
        $class = shift;
        print $class->name, " goes ", $class->sound, "\n";
    }

    sub eat {
        $class = shift;
        $food = shift;
        print $class->name, " eats ",$food, "\n";
    }

    sub color {
        $class = shift;
        print $class->name, " has ", ${$class}{Color}, " color\n";
    }

    sub name {
        $class = shift;
        ref($class) ? (${$class}{'Name'}) : ("An unamed $class");
    }

    sub new {
        $class = shift;
        $name = shift;
        $self = {Name=>$name, Color=>$class->default_color};
        bless $self, $class;
    }

}

{ package Horse;
    @ISA = qw(Animal);
    sub sound {qw(Neigh)};
    sub default_color{'Brown'};
}

{ package Sheep;
    @ISA = qw(Animal);
    sub sound {qw(Baaah)};
    sub default_color{'White'};
}

$horse = Horse->new('Chetak');
$horse->speak;
$horse->eat('Long grass');
$horse->color;

Horse->new();
Horse->speak;
Horse->eat('Long grass');
Horse->color;

$sheep = Sheep->new('Chimpu');
$sheep->speak;
$sheep->eat('Small grass');
$sheep->color;

Sheep->new();
Sheep->speak;
Sheep->eat('Small grass');
Sheep->color;

Reply via email to