2010-09-10 57 views
0

我想寫一個嵌套的if語句的條件,但還沒有找到一個很好的例子使用或在if語句。下面elsif條件失敗,並允許嵌套在它下面的代碼火災如果$status == 6我的Perl腳本中的if-elsif-else塊有什麼問題?

if ($dt1 > $dt2) {do one thing} 
elsif(($status != 3) || ($status != 6)) { do something else} 
else {do something completely different} 

我想,以避免爲每個條件作爲實際居住在這裏的代碼中的另一個ELSIF是幾線長。

+0

@mose:需要更多的上下文。你能提供更多的代碼嗎? – Dummy00001 2010-09-10 10:06:50

+3

'($ status!= 3)|| ($ status!= 6)'總是如此。 – flies 2010-09-10 14:53:12

+0

** @蒼蠅:**如果狀態爲「undef」,該怎麼辦? – vol7ron 2010-09-10 17:37:54

回答

1

將帶有var名稱/值的print語句放入每個分支中會很有幫助。
您可以看到elsif分支始終運行,因爲$status != 3 || $status != 6對於任何值$status都是正確的。

8

你的邏輯錯了,你的elseif塊總是返回true。我想你的意思是使用AND而不是OR。考慮下面的代碼片段

foreach $status (1 .. 10) { 
    if (($status != 3) && ($status != 6)) { 
     print "$status => if\n"; 
    } else { 
     print "$status => else\n"; 
    } 
} 

這將輸出

1 => if 
2 => if 
3 => else 
4 => if 
5 => if 
6 => else 
7 => if 
8 => if 
9 => if 
10 => if 

如果有幫助你的思維,條件是!東西|| !東西總是可以改寫成!(東西是& &)。如果你把它應用到你的案例上面,你會說!(3 & & 6),並且看到一個數字不能同時是3和6,它總是假的

+7

這些轉換規則被稱爲[德摩根定律](http://en.wikipedia.org/wiki/De_Morgan's_laws)。 – daxim 2010-09-10 10:43:55

6

你說你問這是因爲代碼是幾行。解決這個問題。 :)

if($dt1 > $dt2)      { do_this_thing() } 
elsif(($status != 3) || ($status != 6)) { do_this_other_thing() } 
else          { do_something_completely_different() } 

現在,您在塊中沒有多行,並且所有內容都相鄰。你必須弄清楚這些狀況會是怎樣,因爲任何值是不是3或6。不:)

也許你想用and

if($dt1 > $dt2)     { do_this_thing() } 
elsif($status != 3 and $status != 6) { do_this_other_thing() } 
else         { do_something_completely_different() } 
+2

某些值由例如'Perl6 :: Junction'可能不同意:-) – rafl 2010-09-10 10:48:43

+0

我在想連接點,但我猜這不是問題。 :) – 2010-09-10 12:06:28