在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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.
|
请发表评论