Perl 入門指南 - my 與 use
- Get link
- X
- Other Apps

Perl 入門指南 - my 與 use
Perl 模組庫 (library) 中的 strict 與 warnings 促使程式有較安全的寫法

Perl 中這些常用的模組被稱為 Pragmas 。
例如下面程式沒有加入 strict 與 warnings
#!/usr/bin/env perl
sub subroutine1 {
print "$sn";
}
sub subroutine2 {
$s = "There is no spoon.";
print "$sn";
}
$s = "The problem is choice.";
print "$sn";
subroutine1;
subroutine2;
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:demo7.pl
# 功能:示範 Perl 程式
# 作者:張凱慶
# 時間:西元 2013 年 1 月
基本執行上不會有什麼問題

可是這不是安全的寫法,因為我們在很多地方都用了 $s 變數 (variable) ,當程式越寫越長,就越有需要區分變數或識別字名稱是屬於哪一個命名空間的。上例中如果加入 strict 與 warnings ,這就需要用到 use 函數 (function) ,如下
#!/usr/bin/env perl
use strict;
use warnings;
sub subroutine1 {
print "$sn";
}
sub subroutine2 {
$s = "There is no spoon.";
print "$sn";
}
$s = "The problem is choice.";
print "$sn";
subroutine1;
subroutine2;
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:demo8.pl
# 功能:示範 Perl 程式
# 作者:張凱慶
# 時間:西元 2013 年 1 月
執行時直譯器會給我們警告訊息

簡單說就是挑出太多地方用 $s ,卻沒有宣告 $s 的使用範圍。這時候我們可以將程式加入 my 函數,用以宣告區域變數 (local variable)
#!/usr/bin/env perl
use strict;
use warnings;
sub subroutine1 {
print "$_[0]n";
}
sub subroutine2 {
my $s = "There is no spoon.";
print "$sn";
}
my $s = "The problem is choice.";
print "$sn";
subroutine1($s);
subroutine2;
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:demo9.pl
# 功能:示範 Perl 程式
# 作者:張凱慶
# 時間:西元 2013 年 1 月
安全寫法對於發展大型程式會有一定的幫助,不然太多全域變數會讓直譯器很難處理的。接下來我們要來發展一個編密碼的軟體,先來看看具有編碼、解碼核心功能的 Encrypt 模組吧!
中英文術語對照 | |
---|---|
模組庫 | library |
變數 | variable |
函數 | function |
區域變數 | local variable |
您可以繼續參考
軟體開發
- 特別變數
- my 與 use
- Encrypt 模組
- new 方法
- 編碼與解碼
- 認識 CPAN
相關目錄
回 Perl 入門指南
回 Perl 教材
回首頁
參考資料
http://perldoc.perl.org/perlintro.html
http://www.tutorialspoint.com/perl/perl_my.htm
訂閱:
張貼留言 (Atom)
window.___gcfg = { 'lang': 'zh-TW' };
- Get link
- X
- Other Apps
沒有留言:
張貼留言