Perl 入門指南 - Encrypt 模組





































Perl 入門指南 - Encrypt 模組






物件導向程式設計 (object-oriented programming) 最重要的就是設計物件 (object) , Perl 是用模組當成物件設計的模板




其他物件導向程式語言大都是以類別 (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



您可以繼續參考
軟體開發

  • 特別變數

  • my 與 use

  • Encrypt 模組

  • new 方法

  • 編碼與解碼

  • 認識 CPAN





相關目錄

回 Perl 入門指南
回 Perl 教材
回首頁



參考資料

http://perldoc.perl.org/perlootut.html
http://www.tutorialspoint.com/perl/perl_oo_perl.htm







沒有留言:




















window.___gcfg = { 'lang': 'zh-TW' };





Popular posts from this blog

迅雷 Thunder 7.9.43.5054 免安裝版 (9.1.41.914 安裝版) - 支援BT下載的萬用 檔案下載工具

qBittorrent 4.1.1 免安裝中文版 - 取代uTorrent的BT下載器

嘸蝦米輸入法免安裝版 1.0.13.589 - 唯一只用英文字母輸入的中文輸入法