标签:
来源:
http://www.cnblogs.com/itech/archive/2012/08/21/2649580.html
1 sub UNIVERSAL::log() 2 { 3 my($self,$msg)=@_; 4 print "$self: $msg\n"; 5 }
1 package Critter; 2 sub new { bless {} }
如果你希望用户不仅能够用 "CLASS->new()" 这种形式来调用你的构造函数,还能够以 "$obj->new()" 这样的形式来调用的话,那么就这么做:
1 sub new { 2 my $this = shift; 3 my $class = ref($this) || $this; #ref支持了“$obj->new()”形式的调用(感觉是获得类名) 4 my $self = {}; 5 bless $self, $class; 6 $self->initialize(); 7 return $self; 8 }
一个方法就是一个简单的子程序
1 my $fred = Critter->find("Fred"); 2 $fred->display("Height", "Weight");
1 my $fred = Critter::find("Critter", "Fred"); 2 Critter::display($fred, "Height", "Weight");
简单示例
简单示例 1、说明 本程序演示了在Perl中如何进行面向对象编程:演示程序包含两个文件:person.pl 和 person.pm,把 person.pl 和 person.pm 放在当前目录下,运行"perl person.pl"即可以看到结果。person.pm定义了名为person的类。person.pl中创建了person类的实例,并测试了person的成员方法。 2、person.pm的内容 #!/usr/bin/perl -w package person; use strict; sub new { my $class = shift(); print("CLASS = $class\n"); my $self = {}; $self->{"name"} = shift(); $self->{"sex"} = shift(); bless $self, $class; return $self; } sub getName { my ($self) = @_; return $self->{"name"}; } sub setName { my ($self, $name) = @_; $self->{"name"} = $name; } sub getSex { my ($self) = @_; return $self->{"sex"}; } sub setSex { my ($self, $sex) = @_; $self->{"sex"} = $sex; } 3、person.pl的内容 #!/usr/bin/perl -w use strict; use person; sub main() { my $tom = person->new("Tom", "male"); my $kiss = person->new("Kiss", "female"); my @persons = ($tom, $kiss); for my $p (@persons) { printf("NAME: %s\tSEX: %s\n", $p->getName(), $p->getSex()); } } &main(); 4、程序运行结果 CLASS = person CLASS = person NAME: Tom SEX: male NAME: Kiss SEX: female
http://bbs.chinaunix.net/thread-980909-1-1.html
http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=770196
标签:
原文地址:http://www.cnblogs.com/spriteflk/p/5743869.html