免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1288 | 回复: 1
打印 上一主题 下一主题

求助一个关于Perl 继承 bless的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-10-26 17:15 |只看该作者 |倒序浏览
各位前辈好,本人初学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

论坛徽章:
0
2 [报告]
发表于 2012-10-26 17:22 |只看该作者
回复 1# aaron_lidesheng
  1. sub new {
  2.         my $type = shift;
  3.         my $this = {};
  4.         $this->{"Bean"} = "Colombian";
  5.         bless $this, $type;
  6.         return this;        # $this !!!
  7. }

复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP