Perl中的bless的理解

Posted yanzibuaa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Perl中的bless的理解相关的知识,希望对你有一定的参考价值。

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

 

[[email protected]:~]$ 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;



[[email protected]:~]$ 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;

[[email protected]:~]$ 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();

[[email protected]:~]$  ./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

  以下为错误的使用: 

[[email protected]:~]$ 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();

[[email protected]:~]$ ./wrong_bless.pl   
Can‘t call method "sleep" on unblessed reference at ./wrong_bless.pl line 11.

  

以上是关于Perl中的bless的理解的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Perl 5.12 中从 C 创建一个 qr//?

如何有条件地将 C 代码片段编译到我的 Perl 模块?

perl中的队列

调用模板化成员函数:帮助我理解另一个 *** 帖子中的代码片段

如何理解这段代码片段中的两对括号?

代码签名的应用程序与其 Blessed Helper 的代码签名不匹配