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

I'm trying to make 'objFood' inherit from 'Object', but it doesn't seem to want to. @ISA doesn't want to do anything. Here are the packages in question:

#----------------------------------------------- package Object; #----------------------------------------------- sub create { my ($pkg, $name, $weight) = @_; my $obj = bless { "name" => $name, "weight" => $weight, "created" => time, }, $pkg; return $obj; } #----------------------------------------------- package objFood; #----------------------------------------------- @objFood::ISA = qw(Object); sub new { my ($pkg, $name, $weight, $size, $life) = @_; my $obj = $pkg->create($name, $weight); $obj->{"size"} = $size; $obj->{"life"} = $life; return $obj; }


To call it I use, for example:
my $obj1 = objFood->new('cheese', 1, 3, 600);


The error message I get is:
Can't locate object method "create" via package "objFood" (perhaps you forgot to load "objFood"?) at ./nat line 141.


Any thoughts?

Thanks in advance,
--
Dave.

Replies are listed 'Best First'.
(jeffa) Re: Inheritance not working...
by jeffa (Bishop) on Mar 08, 2003 at 13:39 UTC
Re: Inheritance not working...
by adrianh (Chancellor) on Mar 08, 2003 at 13:45 UTC

    My guess is that you have the two packages in different files. In which case you have to ensure that Object package is loaded by the file containing objFood.

    Either use use base qw(Object) instead of the assignment to @ISA, or do an explicit use Object in the objFood file.

Re: Inheritance not working...
by hv (Prior) on Mar 08, 2003 at 16:53 UTC

    My guess is that you have these packages inline in your program, declared below your actual program code. If that is the case, the problem is likely to be that the line:

    @objFood::ISA = qw(Object);
    is not getting executed - don't forget that an assignment like that happens at runtime, not at compile time.

    If you put your packages in a separate file and load them via "use" or "require", file-scope statements like that will get executed at the point the package is loaded. Alternatively, while the packages remain inline in the script you can either move the @ISA assignment earlier in the script, or wrap it in a BEGIN block:

    BEGIN { @objFood::ISA = qw(Object); }

    Hugo
Re: Inheritance not working...
by bart (Canon) on Mar 09, 2003 at 12:21 UTC
    My guess is that this code comes straight from your script, somewhere near the back. Am I right? In that case, you're probably trying to run objFood->new before @objFood::ISA is even set.

    Try assigning to @ISA in a BEGIN block.

    BEGIN { @objFood::ISA = qw(Object); }

    The reason why you don't have to do that when the classes are in their own module, is the fact that the bare code in a module is run as soon as the file is compiled, through use.