• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Perl中的bless的理解

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

bless有两个参数:对象的引用、类的名称。 
类的名称是一个字符串,代表了类的类型信息,这是理解bless的关键。 
所谓bless就是把 类型信息 赋予 实例变量。 

 

[xywang@mnsdev13:~]$ cat Person.pm 
#!/usr/bin/perl -w
package Person;
use strict;

sub sleep() {
       my ($self) = @_;
       my $name = $self->{"name"};

       print("$name is person, he is sleeping\n");
}

sub study() {
       my ($self) = @_;
       my $name = $self->{"name"};

       print("$name is person, he is studying\n");
}
return 1;



[xywang@mnsdev13:~]$ cat Dog.pm 
#!/usr/bin/perl -w
package Dog;
use strict;

sub sleep() {
       my ($self) = @_;
       my $name = $self->{"name"};

       print("$name is dog, he is sleeping\n");
}

sub bark() {
       my ($self) = @_;
       my $name = $self->{"name"};

       print("$name is dog, he is barking\n");
}

return 1;

[xywang@mnsdev13:~]$ cat bless.pl 
#!/usr/bin/perl
use strict;
use Person;
use Dog;

sub main()
{
       my $object = {"name" => "tom"};

       # 把"tom"变为人
       bless($object, "Person");
       $object->sleep();
       $object->study();

       # 把"tom"变成狗
       bless($object, "Dog");
       $object->sleep();
       $object->bark();

       # 再把"tom" 变成人
       bless($object, "Person");
       $object->sleep();
       $object->study();
}

&main();

[xywang@mnsdev13:~]$  ./bless.pl   
tom is person, he is sleeping
tom is person, he is studying
tom is dog, he is sleeping
tom is dog, he is barking
tom is person, he is sleeping
tom is person, he is studying

  以下为错误的使用: 

[xywang@mnsdev13:~]$ cat wrong_bless.pl  
#!/usr/bin/perl
use strict;
use Person;
use Dog;

sub main()
{
       my $object = {"name" => "tom"};

       #没有把类型信息和$object绑定,因此无法获知$object有sleep方法
       $object->sleep();
       $object->study();
}

&main();

[xywang@mnsdev13:~]$ ./wrong_bless.pl   
Can't call method "sleep" on unblessed reference at ./wrong_bless.pl line 11.

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Perl流程控制语句发布时间:2022-07-22
下一篇:
perl学习笔记发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap