Here's a simpler script that illustrates the problem:
#!/usr/bin/perl use strict; use warnings; my $x; 1 ? $x = 1 : $x = 0; print "Without parentheses, \$x = $x\n"; 1 ? ($x = 1) : ($x = 0); print "With parentheses, \$x = $x\n";
He produces this conclusion:
Without parentheses, $x = 0 With parentheses, $x = 1
I am not sure that the connection between the destination and ?: Can be fully explained by the priority of the operator. (For example, I believe that C and C ++ can behave differently in some cases.)
Run perldoc perlop and find the "Conditional perldoc perlop " or look here ; he covers this exact question (more briefly than I am here).
In any case, I think that using the if / else would be clearer than using the ?: Operator. Or, since both true and false branches are assigned to the same variable, is it better to use ?: To change this:
exists $testOverrides{$testName}{reps} ? $reps = $testOverrides{$testName}{reps} : $reps = $testDefaults{system_test_reps};
:
$reps = ( exists $testOverrides{$testName}{reps} ? testOverrides{$testName}{reps} : $testDefaults{system_test_reps} );
But then again, the fact that I had to wrap the line to avoid scrolling is a good indicator that if / else will be clearer.
You can also consider using the // operator if you are not stuck in an antique version of Perl that does not support it. (It was introduced by Perl 5.10.) It is also known as the "specific or" operator. It:
$x // $y
equivalently
defined($x) ? $x : $y
So you can write:
$reps = $testOverrides{$testName}{reps} // $testDefaults{system_test_reps};
This does not have exactly the same semantics, as it validates an expression using defined rather than exists ; it will behave differently if $testOverrides{$testName}{reps} exists but has the value undef .
Keith thompson
source share