Perl三元条件运算符

前端之家收集整理的这篇文章主要介绍了Perl三元条件运算符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在脚本中编写更高效的代码,并且有时会实现三元条件运算符.在循环中使用三元条件运算符时,我无法理解为什么会得到额外的结果:

#!/usr/bin/perl

use strict;
use warnings;

my @array = ('Serial = "123"','Serial = "456"','Serial = "789"');
my ($test1,$test2);
foreach my $a (@array){
        !$test1 ? $test1 = $a  : $test1 .= " AND " . $a;
}
foreach my $b (@array){
        if (!$test2) {
                $test2 = $b
        } else {
                $test2 .= " AND " . $b;
        }
}
print "Test1: $test1\n";
print "Test2: $test2\n";

输出

~/bin/test.pl
Test1: Serial = "123" AND Serial = "123" AND Serial = "456" AND Serial = "789"
Test2: Serial = "123" AND Serial = "456" AND Serial = "789"

Test1输出有一个额外的“Serial =”123“,我做错了什么?

解决方法

作业的优先级低于?.这个

!$test1 ? $test1 = $a  : $test1 .= " AND " . $a;

相当于:

(!$test1 ? $test1 = $a  : $test1) .= " AND " . $a;

因此,首先$test1将变为Serial =“123”,然后立即追加AND Serial =“123”.

试试这个:

!$test1 ? ($test1 = $a)  : ($test1 .= " AND " . $a);

更好的解决方案是:

$test1 = !$test1 ? $a  : $test1 . " AND " . $a;

使用三元运算符进行副作用会变得非常混乱,我建议避免它.

编辑

正如MuIsTooShort join(‘AND’,array)所指出的那样,在您的情况下,它将是最简洁和可读的解决方案.

猜你在找的Perl相关文章