- 论坛徽章:
- 0
|
各位前辈好,本人初学Perl,在学习Perl OOO时 被bless问题深深困扰,先贴出我的学习代码和问题,希望各位大侠给指条明路:
父类 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;
require Bean;
@ISA = qw(Exporter, Bean);
@EXPORT = qw(setImports, declareMain, closeMain);
sub new {
my $type = shift;
$this = Bean->new();
$this->{'Coffee'} = 'Instant';
bless $this, $type;
return $this;
}
sub setCoffeeType {
my ($class, $name) = @_;
$class->{'Coffee'} = $name;
print "Set coffee type to $name \n";
}
1;
调用Perl test.pl
push (@INC, 'cd');
use Coffee;
$cat = new Coffee;
print "\n-----------------------------Initial values-------------------\n";
print "Coffee: $cat->{'Coffee'} \n";
print "Bean: $cat->{'Bean'} \n";
print "\n-----------------------------Change Bean Type-----------------\n";
$cat->setBeanType('Mixed');
print "Bean Type is now $cat->{'Bean'} \n";
print "\n-----------------------------Change Coffee Type----------------\n";
$cat->setCoffeeType('Instant');
print "Type of coffee: $cup->{'Coffee'} \n";.
问题:
一运行test.pl,就报错Can't bless non-reference value at C:/Software/Programming/WorkSpace/Perl Practice/Coffee.pm line 17.
也就是Coffee构造函数中
bless $this, $type;
究竟是什么原因呢,求解。 本人环境是windows xp |
|