Perl三元条件运算符 [英] Perl ternary conditional operator
问题描述
我正在尝试在脚本中编写更高效的代码,并且有时会实现三元条件运算符.我不明白为什么在循环中使用三元条件运算符会得到额外的结果:
I'm trying to write more efficient code in my scripts and have been implementing ternary conditional operators on occasion. I can't understand why I am getting an additional result when using a ternary conditional operator in a loop:
#!/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 output has an additional "Serial = "123", What am I doing wrong?
推荐答案
工作分配的优先级低于?
.这个
Assignment has lower precendence than ?
. This
!$test1 ? $test1 = $a : $test1 .= " AND " . $a;
等效于此:
(!$test1 ? $test1 = $a : $test1) .= " AND " . $a;
因此,首先$test1
将变为Serial = "123"
,然后紧随其后添加AND Serial = "123"
.
So first $test1
will become Serial = "123"
and then AND Serial = "123"
gets appended immediately after.
尝试一下:
!$test1 ? ($test1 = $a) : ($test1 .= " AND " . $a);
一个更好的解决方案是:
A better solution would be this:
$test1 = !$test1 ? $a : $test1 . " AND " . $a;
使用三元运算符产生副作用会变得很混乱,我建议避免使用它.
Using the ternary operator for side effects can get quite messy and I'd recommend to avoid it.
修改
如MuIsTooShort join(' AND ', array)
所述,这将是您案例中最简洁,最易读的解决方案.
As noted by MuIsTooShort join(' AND ', array)
would be the most concise and readable solution in your case.
这篇关于Perl三元条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!