perl inheritance and directory structure -
i'm trying learn inheritance in perl.
this directory structure:
perldir
perldir\child.pl
perldir\mylib
perldir\mylib\parent.pm
parent.pm
package parent; sub new { $class = shift; $self = { _first => shift, _last => shift }; bless $self, $class; } sub getfirstname { ($self) = @_; return $self->{ _first }; } 1; child.pl
package child; use parent 'mylib::parent'; sub new { $class = shift; $self = parent->new( shift, shift ); bless $self, $class; } $obj = new child('jack', 'sparrow'); print $obj->{_first},' ',$obj->{_last}; print "\n",$obj->getfirstname(); #error the error thrown on last line is: can't locate object method "getfirstname" via package "achild" @ child.pl line 13;
the program works if 1 of following:
1. have both files under directory mylib.
2. replace
use parent 'mylib::parent' with
use mylib::parent; @isa = ('parent'); is possible program work using 'use parent' , child class in different directory?
==========================
updated question based on choroba's answer.
ok changed classes reflect following:
parent.pm
package mylib::parent; sub new { $class = shift; $self = { _first => shift, _last => shift }; bless $self, $class; } sub getfirstname { ($self) = @_; return $self->{ _first }; } 1; child.pl
package child; use parent 'mylib::parent'; sub new { $class = shift; $self = mylib::parent->new( shift, shift ); bless $self, $class; } $obj = new child('jack', 'sparrow'); print $obj->{_first},' ',$obj->{_last}; print "\n",$obj->getfirstname(); the above works fine. consider want child class in same directory parent.pm.
perldir\mylib\childtwo.pl
package childtwo; #or package mylib::childtwo; use parent 'mylib::parent'; #or use parent 'parent'; sub new { $class = shift; $self = mylib::parent->new( shift, shift ); #or parent->new(shift, shift); bless $self, $class; } $obj = new childtwo('jack', 'sparrow'); #or new mylib::childtwo('jack','sparrow'); print $obj->{_first},' ',$obj->{_last}; print "\n",$obj->getfirstname(); 1; the above not work. can childtwo.pl work along child.pl without using 'use lib'?
you have make mind: either parent package's name parent, in child.pl:
use parent 'parent'; and tell perl search it:
perl -imylib child.pl or use lib
use findbin; use lib "$findbin::bin/mylib"; or, package's name mylib::parent, have fix package declaration:
package mylib::parent; and call correct constructor:
my $self = mylib::parent->new( shift, shift );
Comments
Post a Comment