學習perl的unless控制結構

來源:互聯網
上載者:User

例如:

複製代碼 代碼如下:unless ($fred =~ /^([A-Z_]\w*$/i) {
print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

使用unless意味著,要麼條件為真,要麼執行某塊代碼。這就好像使用if控制結構來判斷相反的條件。另一種說法是它類似於獨立的else子句。也就是說,當看不懂某個unless語句時,可以用如下的if語句來代替:複製代碼 代碼如下:if ($fred =~ /^([A-Z_]\w*$/i) {
//什麼都不做
} else {
print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

如此操作與運行效率高低無關,兩種寫法應該會被統譯成相同的內部位元組碼。另外一個改寫的方法,就是以取反操作符!來否定條件:複製代碼 代碼如下:if ( ! ($fred =~ /^([A-Z_]\w*$/i) ) {
print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

通常應該選擇最容易理解的方法來寫代碼,因為這通常對於維護程式員來說也是最容易理解的。如果用if來表達最合適,那麼就這麼寫也行。但是更多的情況下使用unless能使你的表達更加自然。

unless附帶的else子句

其實哪怕是在unless結構中也可以使用else語句,雖然支援這樣的文法,但是可能會導致困惑:

複製代碼 代碼如下:#!/usr/bin/perl -w
unless ($mon =~ /^Feb/) {
print "This month has at least thirty days.\n";
} lese {
print "Do you see what's going on here?\n";
}
#如果用if語句我們可以寫成這樣:
if ($mon =~ /^Feb/) {
print "Do you see what's going on here?\n";
} else {
print "This month has at least thirty days.\n";
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.