unless,until, for, while, last, next,foreach redo

unless
在if 控制結構中,只有條件爲真時,才執行塊中的代碼。若是你想在條件爲假時執行,可使用unless:除非條件爲真,不然執行塊中的代碼
unless($fred =~ /^[A-Z_]\w*$/i){
print 「The value of \$fred doesn’t look like a Perl identifier name.\n」;
}

unless 和else 語句一塊兒使用
unless 中也能夠有else 語句。雖然語法上支持,但可能引發混淆:
unless ($mon =~ /^Feb/){
print 「This month has at least thirty days.\n」;
}else{
print 「Do you see what’s going on here?\n」;
}

until 控制結構
有時,但願將while 循環的條件部分取反。此時,可使用until:
until($j > $i){
$j *=2;
}

表達式修飾符

爲了獲得更緊湊的形式,表達式後能夠緊接控制修飾語。如,if 修飾語能夠像if 塊那樣使用:
print 「$n is a negative number.\n」if $n<0;
還有一些其它的修飾語:
&error(「Invalid input」) unless &valid($input);
$i *= 2 unitl $i > $j;
print 「」, ($n += 2) while $n <10;
&greet($_) foreach @person;

last 操做
last 會馬上結束循環。(這同C 語言或其它語言中的「break」語句相似)。它從循環塊中「緊急退出」。當執行到last,循環即結束,以下例:
#輸出全部出現fred 的行,直到碰見_ _END_ _標記
while(<STDIN>){
if(/_ _ END_ _/){
#這個標記以後不會有其它輸入了
last;
}elsif(/fred/){
print;
}
}
##last 跳轉到這裏##

Perl 的5 種循環體分別是for, foreach, while, until,以及「裸」塊◆。花括號括起來的if 塊,子程序◆不算。在上面的例子中,last 對整個循環塊其做用。

next 操做

有時還不但願結束循環,但本次循環已經結束。這種狀況下,next 是很是適用的。它跳到當前循環塊的最後面(塊內)next 以後,又會進入下一輪循環(這和C 或者相似語言的「continue」類似,但不同):
css

  1. #分析輸入文件的單詞
    less

  2. while(<>){
    ide

  3. foreach(split){ #將$_分拆成單詞,並依次賦給$_
    測試

  4. $total++;
    spa

  5. next if/\W/; #不是「words」的被跳過k
    code

  6. Perl 語言入門(第四版)
    input

  7. blei@163.com 132 / 201 9/21/2006
    it

  8. $valid++;
    入門

  9. $count{$_}++; #對每一個單詞進行計數
    ast

  10. ##next 跳到這裏##

  11. }

  12. }

  13. print 「total things = $total, valid words = $valid\n」;

  14. foreach $word (sort keys %count){

  15. print 「$word was seen $count{$word} time.\n」;

  16. }

redo 操做
循環控制的第三個操做是redo。它會調到當前循環塊的頂端,不進行條件表達式判斷以及接着本次循環.
  1. #輸入測試

  2. my @words = qw{ fred barney pebbles dinoWilma betty };

  3. my $errors = 0;

  4. foreach(@words){

  5. ##redo 跳到這裏##

  6. print 「Type the word ‘$_’:;

  7. chomp(my $try =<STDIN>);

  8. if($try ne $_){

  9. print 「sorry –That’s not right.\n\n」;

  10. $errors++;

  11. redo; #跳轉到循環頂端

  12. }

  13. }

  14. print 「You’ve completed the test, with $errors errors.\n」;

next 和redo 的最大區別在於,next 會進入下一次循環,而redo 會繼續執行本次循環
相關文章
相關標籤/搜索