Perl面向對象--類

最近工作當中要用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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章