面向对象之继承篇
Bean.pm (父类)
==================================
package Bean;
require Exporter;
@ISA=qw(Exporter);
@EXPORT=qw(setBeanType);
sub new{
my $type=shift;
my $this={};
$this->{'Bean'}='Colombian';
bless $this,$type;
return $this;
}
sub setBeanType{
my($class,$name)=@_;
$class->{'Bean'}=$name;
print "Set Bean to $name \n";
}
1;
=====================================
Coffee.pm (子类)
=====================================
package Coffee;
require Exporter;
use Bean;
@ISA=qw(Exporter Bean);
@EXPORT=qw(setBeanType setCoffeeType);
sub setCoffeeType{
my($class,$name)=@_;
$class->{'Coffee'}=$name;
print "set Coffee type to $name \n";
}
sub new{
my $type=shift;
my $this=Bean->new();
$this->{'Coffee'}='instant';
bless $this,$type;
return $this;
}
1;
==================================
继承案例
#!/usr/bin/perl
push(@INC,`pwd`);
use Coffee;
$cup=new Coffee;
print $cup->{'Coffee'};
print "\n";
print $cup->{'Bean'};
print "\n";
$cup->setBeanType('Mixed');
$cup->setCoffeeType('mmmm');
补充资料:
@INC 是由use,require在加载模块时所搜寻的路径.
@ISA perl类的继承是通过@ISA数组实现的.@ISA数组不需要在任何包中定义,然而,一旦被定义,perl就把它看作目录名的特殊数组.它与@INC数组类似,@INC是包含文件的寻找路径.@ISA数组含有类(包)名,当一个方法在当前包中未找到时,就可以到@ISA中的包去寻找.@ISA中还含有当前类继承的基类名.