2012-09-12 24 views
2

我敲入了简单的嵌套if语句。perl嵌套,如果还是别的

要求如下。

if (Condition1) { 
    if (Condition2) { 
     print "All OK"; 
    } 
    else { 
     print "Condition1 is true but condition2 not"; 
    } 
    else {print "Condition1 not true"; 
} 

是否有可能在Perl编写代码或有任何其他短/更好的方式来满足这个条件?

回答

2

if条件1为真子句是丢失的收盘}应权前的最后别的插入。

尝试排队事情是这样的:

if (...) { 
    if (...) { 
     ... 
    } 
    else { 
     ... 
    } 
} 
else { 
    .... 
} 
+0

感谢您指出小错误...很大 – Mahesh

1

您可以使用given..when如果您的Perl> = 5.10版本。

use v5.14; 

my $condition1 = 'true'; 
my $condition2 = 'True'; 

given($condition1) { 
    when (/^true$/) { 
     given($condition2) { 
      when (/^True$/) { say "condition 2 is True"; } 
      default   { say "condition 2 is not True"; } 
     } 
    } 
    default { say "condition 1 is not true"; } 
} 
+6

,嗯,你可以* *,但为什么要?该代码是更多的工作来阅读和理解。 – ysth

+0

这只是一个解决方案。 –

2

TIMTOWTDI点菜ternary operator

print $condition1 
     ? $condition2 
     ? "All OK\n" 
     : "Condition 1 true, Condition 2 false\n" 
     : "Condition 1 false\n"; 
1

如何:

if (Condition1=false) { 
    print "Condition1 not true"; 
} 
elsif (Condition2=True) { 
    print "All OK"; 
} 
else { 
    print "Condition1 is true but condition2 not"; 
} 
+1

虽然这是正确的,但它是非直观的,并且难以维护 – Zaid

+0

同意。 OP如何要求更短或更好的解决方案,并且这个更短:)。 – librarian

0
if (Condition1) { 
    if (Condition2) { 
     print "Both true"; 
    } 
    else { 
     print "Condition1 is true, Condition2 false"; 
    } 
} 
else { 
    if (Condition2) { 
     print "Condition1 false Condition2 is true"; 
    } 
    else { 
     print "Both false"; 
    } 
} 
0
#OR condition 
if (($file =~ /string/) || ($file =~ /string/)){ 
} 

#AND condition 
if (($file =~ /string/) && ($file =~ /string/)){ 
}