最近工作当中要用Perl写一些脚本,发现Perl面象对象的编程比较生疏,所以重新学习一下,顺便做个记录。
Perl中的类就是一个Perl的包(package)。Perl的类实际上就是一个哈希表的引用。Perl使用关bless函数来生成类的引用。
bless ClasssRef [,ClassName];
看代码,如何定义一个类:
##Foo.pm
package Foo;
#require Exporter;
#@EXPORT =(do_sth);
#构造函数
sub new{
my $class = shift;
my $this = {};
##属性
$this->{name} = "Foo";
bless $this,$class;
return $this;
}
#方法
sub do_sth{
print "Do something here\n";
}
1;
现在,你就可以在代码中引用类Foo,
##test.pl
use Foo;
my $f = Foo->new();
$f->do_sth();