Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
嵌套';如果';或者Perl中的其他东西_Perl_If Statement - Fatal编程技术网

嵌套';如果';或者Perl中的其他东西

嵌套';如果';或者Perl中的其他东西,perl,if-statement,Perl,If Statement,我插入了一个简单的嵌套if语句 要求如下 if (Condition1) { if (Condition2) { print "All OK"; } else { print "Condition1 is true but condition2 not"; } else {print "Condition1 not true"; } 是否可以用Perl编写此代码,

我插入了一个简单的嵌套if语句

要求如下

if (Condition1) {
    if (Condition2) {
        print "All OK";
    }
    else {
        print "Condition1 is true but condition2 not";
    }
    else {print "Condition1 not true";
}
是否可以用Perl编写此代码,或者是否有其他简短或更好的方法来满足此条件?

如果您的Perl>=5.10版本,则可以使用given

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"; }
}
阿拉:

如果条件1为真。子句缺少结束语
}
,应该在最后一个else之前插入

试着这样排列:

if (...) {
    if (...) {
        ...
    }
    else {
        ...
    }
}
else {
    ....
}
那么:

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

呃,你可以,但你为什么要这么做?这段代码需要阅读和理解的工作量要大得多。虽然这是正确的,但它并不直观,而且有点难以维护。然而,OP要求提供一个更短或更好的解决方案,这是更短的:)。糟糕的Perl。不会通过“假”和“真”的严格检查。当需要比较时,使用赋值=的运算符错误==。最好不要与真/假值进行比较。如果为true,最好使用标量本身,并且!如果为false,则为标量。需要进行解释。修复了代码。也希望现在足够清楚。
if (Condition1=false) {
     print "Condition1 not true";
}
elsif (Condition2=True ) {
    print "All OK"; 
}
else {
    print "Condition1 is true but condition2 not";  
}
if (!Condition1) {
  print "Condition1 not true";
}
else {
  if (Condition2) {
    print "All OK";
  }
  else {
    print "Condition1 is true but condition2 not";
  }
}
#OR condition
if ( ($file =~ /string/) || ($file =~ /string/) ){
}

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