
其他物件導向程式語言大都是以類別 (class) ,也就是拿 class 來當關鍵字 (keyword) ,然後作為物件的模板。
物件可以有屬性 (attribute) 與方法 (method) , Perl 中物件的方法為模組中的副程式 (subroutine) ,屬性則是方法中特別定義的變數 (variable) 。
基本的 Encrypt.pm 設計如下
#!/usr/bin/perl
use strict;
use warnings;
package Encrypt;
sub new {
my $code = join("", ("a" .. "z"));
return $code;
}
sub getCode {
return "getCode";
}
sub setCode {
return "setCode";
}
sub toEncode {
return "toEncode";
}
sub toDecode {
return "toDecode";
}
1;
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:Encrypt.pm
# 功能:示範 Perl 程式
# 作者:張凱慶
# 時間:西元 2013 年 1 月 裡頭定義了五個方法,其中 new 有一個區域變數 $code
sub new {
my $code = join("", ("a" .. "z"));
return $code;
}"a" .. "z" 會建立一個小寫英文字母表的陣列 (array) ,內建函數 (function) join() 會將這個陣列合併成一個字串,至於第一個參數 (parameter) 則是陣列元素的連接字串,此為空字串,因此 $code 會得到
"abcdefghijklmnopqrstuvwxyz"
這是我們要發展編密碼用的 Encrypt 模組的雛型,我們用以下的程式先來測試一下吧
#!/usr/bin/perl use strict; use warnings; use Encrypt; print Encrypt::new."\n"; print Encrypt::getCode."\n"; print Encrypt::setCode."\n"; print Encrypt::toEncode."\n"; print Encrypt::toDecode."\n"; # 《程式語言教學誌》的範例程式 # http://pydoing.blogspot.com/ # 檔名:encryptdemo.pl # 功能:示範 Perl 程式 # 作者:張凱慶 # 時間:西元 2013 年 1 月
執行結果如下

順利執行無誤,不過嚴格說 Encrypt 還沒真正成為物件的模板,因為這需要能定義屬性的 new 方法咧!
| 中英文術語對照 | |
|---|---|
| 物件導向程式設計 | object-oriented programming |
| 物件 | object |
| 類別 | class |
| 屬性 | attribute |
| 方法 | method |
| 副程式 | subroutine |
| 變數 | variable |
| 陣列 | array |
| 函數 | function |
| 參數 | parameter |
您可以繼續參考
軟體開發
相關目錄
回 Perl 入門指南
回 Perl 教材
回首頁
參考資料
http://perldoc.perl.org/perlootut.html
http://www.tutorialspoint.com/perl/perl_oo_perl.htm
沒有留言:
張貼留言