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
#分析輸入文件的單詞
less
while(<>){
ide
foreach(split){ #將$_分拆成單詞,並依次賦給$_
測試
$total++;
spa
next if/\W/; #不是「words」的被跳過k
code
Perl 語言入門(第四版)
input
blei@163.com 132 / 201 9/21/2006
it
$valid++;
入門
$count{$_}++; #對每一個單詞進行計數
ast
##next 跳到這裏##
}
}
print 「total things = $total, valid words = $valid\n」;
foreach $word (sort keys %count){
print 「$word was seen $count{$word} time.\n」;
}
#輸入測試
my @words = qw{ fred barney pebbles dinoWilma betty };
my $errors = 0;
foreach(@words){
##redo 跳到這裏##
print 「Type the word ‘$_’: 」;
chomp(my $try =<STDIN>);
if($try ne $_){
print 「sorry –That’s not right.\n\n」;
$errors++;
redo; #跳轉到循環頂端
}
}
print 「You’ve completed the test, with $errors errors.\n」;