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”相似,但不一樣):
#分析輸入文件的單詞
while(<>){
foreach(split){ #將$_分拆成單詞,並依次賦給$_
$total++;
next if/\W/; #不是“words”的被跳過k
Perl 語言入門(第四版)
blei@163.com 132 / 201 9/21/2006
$valid++;
$count{$_}++; #對每個單詞進行計數
##next 跳到這裏##
}
}
print “total things = $total, valid words = $valid\n”;
foreach $word (sort keys %count){
print “$word was seen $count{$word} time.\n”;
}
循環控制的第三個操作是redo。它會調到當前循環塊的頂端,不進行條件表達式判斷以及接着本次循環.
#輸入測試
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”;