为什么比较运算符无法正常工作而运算符“ne”块正在工作

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块。

输出:输出

Dad*_*ada 6

问题来自这一行:

if ($tstRunType ne 'Development' || $tstRunType ne 'Production' || $tstRunType ne 'All') {
Run Code Online (Sandbox Code Playgroud)

此条件始终为真:如果$tstRunTypeDevelopment,则它不是Production,并$tstRunType ne 'Production'返回 true (对于 的所有可能值也是如此$tstRunType)。
相反,你应该写:

if ($tstRunType ne 'Development' && $tstRunType ne 'Production' && $tstRunType ne 'All') {
Run Code Online (Sandbox Code Playgroud)

然后,如果$tstRunTypeDevelopmentProduction或 之一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;

  • @LalitKumarSingh 顺便说一句,我发现您到目前为止还没有接受为您的其他问题提供的任何答案(特别是,您有 2 个问题的评分为正,但您没有接受)。请参阅[当有人回答我的问题时我该怎么办?](https://stackoverflow.com/help/someone-answers),并考虑接受解决您问题的答案。 (2认同)