我们使用 Perl 脚本来检查是否有条件。
##code(t1) is as belows:
my @results = (93, 4, 0);
my @param_array = (
[ "50", "<", "stat1", ],
[ "1", "<", "stat2", ],
[ "3", "<", "stat3", ],
);
for ($i=0; $i < @results; $i++) {
print (" " . $results[$i] . " " . $param_array[$i][1] . " " . $param_array[$i][0] . " ");
if ( $results[$i] + 0 < $param_array[i][0] + 0 ) {
print " beend";
}
else {
print " end111";
}
}
Run Code Online (Sandbox Code Playgroud)
结果很奇怪。当 95<50 时,if条件不成立,并打印 end111. 我认为这个说法是对的。
但是当 4 < 1 时,if条件不成立,它也会打印beend. 我认为这种说法是错误的。
为什么会发生这种情况?
###result is as below
perl t1
93 < 50 end111
4 < 1 beend
0 < 3 beend
Run Code Online (Sandbox Code Playgroud)
您应该添加use warnings;到您的代码中,您应该会看到如下警告消息:
Unquoted string "i" may clash with future reserved word
Argument "i" isn't numeric in array element
Run Code Online (Sandbox Code Playgroud)
您还应该添加use strict;到您的代码中,您应该会看到如下编译错误消息:
Bareword "i" not allowed while "strict subs" in use
Run Code Online (Sandbox Code Playgroud)
您需要更改i为$i. 改变:
if ( $results[$i] + 0 < $param_array[i][0] + 0 ) {
Run Code Online (Sandbox Code Playgroud)
到:
if ( $results[$i] + 0 < $param_array[$i][0] + 0 ) {
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出,我认为这是您想要的(尽管您没有明确显示您的预期输出):
93 < 50 end111
4 < 1 beend
0 < 3 beend
Run Code Online (Sandbox Code Playgroud)
注意:您还需要$i在for循环之前声明以满足strict,如果您还没有这样做:
my $i;
Run Code Online (Sandbox Code Playgroud)
这是您的代码的整洁版本,其中包含适当的修复(使用perltidy):
use warnings;
use strict;
my @results = ( 93, 4, 0 );
my @param_array = (
[ "50", "<", "stat1", ],
[ "1", "<", "stat2", ],
[ "3", "<", "stat3", ],
);
for (my $i = 0 ; $i < @results ; $i++ ) {
print( " " . $results[$i] . " " . $param_array[$i][1] . " " . $param_array[$i][0] . " " );
if ( $results[$i] + 0 < $param_array[$i][0] + 0 ) {
print " beend";
}
else {
print " end111";
}
print "\n";
}
Run Code Online (Sandbox Code Playgroud)