perl學習(8) 控制:unless,until,next,redo,last

Perl中實現了所有C 的操作符!

Perl力求代碼最少! 

1.1.unless

unless的含義是:除非條件爲真,否則執行塊中的代碼,和if正好相反

unless($fred=~ /^[A-Z_]\w*$/i){

       print “The value of \$fred doesn’t looklike a Perl identifier name.\n”;

}

else

{

       print “match success\n”;

}

#大寫字母或者下劃線開頭的字符串

 

1.2.until

while 循環的條件部分取反

until($j> $i){

       $j *=2;

} 

1.3.表達式修飾符 

print“$n is a negative number.\n”if $n<0;

&error(“Invalidinput”) unless &valid($input);

$i *=2 unitl $i > $j;

print“”, ($n += 2) while $n <10;

&greet($_)foreach @person;

Perler 一般都喜歡少輸入些字符。簡寫的形式讀起來很像英文:輸出這段消息,如果$n 小於0

條件表達式雖然被放在後面,也是先被求值 

1.4.for

for($i=1; $i <=10; $i++){ #從1到10

       print “I can count to $i;\n”;

}

 

對於Perl 解析器(parser)而言,關鍵字foreach for 是等價的。
for(1..10){ #實際上是foreach 循環,從1到10

       print “I can count to $_!\n”;

} 

1.5.last

last 會立刻結束循環。(這同C 語言或其它語言中的“break”語句類似)。

#輸出所有出現fred 的行,直到遇見_ _END_ _標記

while(<STDIN>){

       if(/_ _ END_ _/){

              #這個標記之後不會有其它輸入了

              last;

       }elsif(/fred/){

              print;

       }

}

##last跳轉到這裏##

 

Perl 的5 種循環體分別是for,foreach, while, until,以及“裸”塊{},last 對整個循環塊其作用。

 

#! /usr/bin/perl -w

use strict;

use warnings ; 

{

   print "test1\n";

   last;

   print "test2";

} 

1.6.next

next 之後,又會進入下一輪循環(這和C 或者類似語言的“continue”相似)

1.7.redo

循環控制的第三個操作是redo。它會調到當前循環塊的頂端,不進行條件表達式判斷以及接着本次循環。(在C 或類似語言中沒有這種操作。) 

#!/usr/bin/perl -w
use strict ;
use warnings; 
#輸入測試
my @words = qw{ fredbarney 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 $errorserror\n"; 

1.8.標籤塊

Larry 推薦標籤均大寫。這會防止標籤和其它標識符衝突,同時也使之在代碼中更突出。同時,標籤很少使用,通常只在很少一部分程序中出現。

這個和c是同樣的,爲了保證邏輯和維護的簡明,儘量不適用goto

goto 

1.9.邏輯操作符

邏輯與AND(&&)

邏輯或OR (||

邏輯或||有另外的含義,perl裏面成爲:短路操作

my$last_name = $last_name{$someone} ||‘(No last name)’

即在%last_name 中不存在$someone時,$last_name = ‘(No last name)’

 邏輯操作符還能用來控制結構

($m< $n) && ($m = $n);

($m> 10) || print“why it it not greater?\n”

1.10.    三元操作符

my$location = &is_weekend($day) ? “home”: “work”;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章