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.

  

05-23 18:29