Lal*_*ngh -2 perl conditional-operator
我有一些从命令行获取的字符串作为参数,如果特定参数已被传递,我需要运行该块,否则它会显示打印语句并退出。
我正在使用两个块,其中在第一个块中我使用ne运算符来检查字符串是否不等于所需的字符串,然后退出程序并eq运算符来检查传递的字符串是否相等,然后执行代码。
下面是我的代码片段:
my $number_args = $ #ARGV + 1;
if ($number_args ne 2) {
print "Usage: perl testAutomation.pl <ExcelSheetName.xlsx> <Production/Development/All>.\n";
exit;
}
my $tstRunSheet = $ARGV[0];
my $tstRunType = $ARGV[1];
if ($tstRunType ne 'Development' || $tstRunType ne 'Production' || $tstRunType ne 'All') {
print "Usage: perl testAutomation.pl <ExcelSheetName.xlsx> <Production/Development/All>.\n";
exit;
}
elsif($tstRunType eq 'Development' || $tstRunType eq 'Production') {
($result1, $result2, $result3, $result4, $result5, $result6, $result7, $result8) = & getXlxsDetails($tstRunSheet, $tstRunType);
}
Run Code Online (Sandbox Code Playgroud)
当我根据elsif块中的要求提供正确的字符串时,它仍然在运行该if块。
问题来自这一行:
if ($tstRunType ne 'Development' || $tstRunType ne 'Production' || $tstRunType ne 'All') {
Run Code Online (Sandbox Code Playgroud)
此条件始终为真:如果$tstRunType是Development,则它不是Production,并$tstRunType ne 'Production'返回 true (对于 的所有可能值也是如此$tstRunType)。
相反,你应该写:
if ($tstRunType ne 'Development' && $tstRunType ne 'Production' && $tstRunType ne 'All') {
Run Code Online (Sandbox Code Playgroud)
然后,如果$tstRunType是Development、Production或 之一All,相应的ne测试将返回 false,使整个条件为 false。
您也可以将此条件写为:
my @run_types = qw(Development Production All);
if (!grep { $tstRunType eq $_ } @run_types) { ...
Run Code Online (Sandbox Code Playgroud)
这样,您不必重复 3 次类似的测试,并且可以轻松添加新的运行类型。
或者,使用正则表达式进行稍微更紧凑的测试:
if ($tstRunType !~ /^(Development|Production|All)$/) {
Run Code Online (Sandbox Code Playgroud)
另请注意,my $number_args = $#ARGV + 1;可以简单地写为my $number_args = @ARGV;。