![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj7_rh3Pat1FuL3F7dPXakmvYkzjjcAL65cu8BD0XMCx48chHOV63IcdrE78nniCx7HiCZA1wMnkxb9FgbED8OJ7VZqlIBN-ii3hxOvV6h2n2bBh2tygX_NvBOtgN-nMOARpBh02gIm7Guj/s800/selection.png)
選擇結構有單一選擇跟多重選擇,兩者都使用 if 陳述 (if statement) , if 為關鍵字 (keyword) 之一,若是多重選擇 if 須與 elsif 或 else 連用。單一選擇,也就是單獨使用 if 陳述如下
if (3 < 5) { print "Oh! 3 is bigger than 5!\n"; }
條件為 if 後面的小括弧,上例為 3 大於 5 ,如果 3 大於 5 為真,程式就會執行條件後大括弧中的程式區塊 (block) 。如果 3 大於 5 為假,程式自然跳過條件後的程式區塊,去找區塊後的第一個陳述 (statement) 執行。
if 與 else 連用,條件為真,執行 if 後的程式區塊,條件為假,就執行 else 後的程式區塊
if (3 < 5) { print "Oh! 3 is bigger than 5!\n"; } else { print "Not Bad! 3 is not bigger than 5!\n"; }
elsif 表示其他的條件,形成 if-elsif-else 的多重選擇,最後的 else 表示以上皆非
if (3 < 5) { print "Oh! 3 is bigger than 5!\n"; } elsif (4 > 5) { print "Oh! 4 is bigger than 5!\n"; } elsif (5 > 5) { print "Oh! 5 is bigger than 5!\n"; } elsif (6 > 5) { print "Of course, 6 is bigger than 5!\n"; } else { print "There is no case :(\n"; }
我們將以上寫成完整的範例程式,如下
#!/usr/bin/env perl print "\n"; if (3 > 5) { print "Oh! 3 is bigger than 5!\n"; } elsif (4 > 5) { print "Oh! 4 is bigger than 5!\n"; } elsif (5 > 5) { print "Oh! 5 is bigger than 5!\n"; } elsif (6 > 5) { print "Of course, 6 is bigger than 5!\n"; } else { print "There is no case :(\n"; } print "\n"; # 《程式語言教學誌》的範例程式 # http://pydoing.blogspot.com/ # 檔名:selection.pl # 功能:示範 Perl 程式 # 作者:張凱慶 # 時間:西元 2013 年 1 月
執行結果如下
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeOMvJFdvTnYEeSBkLV3TU7W8DLxZ2_lYHe-ltXWqv98FWNN4A_2cGajMw8rxBKWMMewJtAJB5xHMrx8V2TWNiz58hzDwp40EaPzHESD5Tpv8HozIlEXeJET2wGVnkjWh4o5hVkuyeye1Q/s800/selection.png)
另舉一例如下
#!/usr/bin/env perl print "\n"; $s = 6; if ($s == 3) { print "3...\n"; } elsif ($s == 4) { print "4...\n"; } elsif ($s == 5) { print "5...\n"; } elsif ($s == 6) { print "6...\n"; } else { print "There is no case :(\n"; } print "\n"; # 《程式語言教學誌》的範例程式 # http://pydoing.blogspot.com/ # 檔名:selection2.pl # 功能:示範 Perl 程式 # 作者:張凱慶 # 時間:西元 2013 年 1 月
這裡的條件為判斷某一變數 (variable) 是否符合某一常數 (constant) ,執行結果如下
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-_MPOV-lxmMc_8xhaEaOdgGX-4T6v_sHKJaB0Kan8VN9mDcSaChpfQVyoq5hHz8Z6BeyniQ51_iaDPWYdbgf_FK_-YQkZ6iWJbAzJyqW5NwzxdM2rv8CXvoZp2WOObQbZa5HSxCJ3hQo7/s800/selection2.png)
複合陳述 (compound statement) 除了選擇結構 (selection structure) 還有重複結構 (repetition structure) ,重複結構也被稱為迴圈 (loop) ,接下來我們就來看看如何使用迴圈吧!
中英文術語對照 | |
---|---|
選擇 | selection |
條件 | condition |
if 陳述 | if statement |
關鍵字 | keyword |
程式區塊 | block |
陳述 | statement |
常數 | constant |
變數 | variable |
複合陳述 | compound statement |
選擇結構 | selection structure |
重複結構 | repetition structure |
迴圈 | loop |
您可以繼續參考
基礎篇
相關目錄
回 Perl 入門指南
回 Perl 教材
回首頁
參考資料
http://perldoc.perl.org/perlintro.html
http://perldoc.perl.org/perlsyn.html
http://www.tutorialspoint.com/perl/perl_conditions.htm
沒有留言:
張貼留言