note
kcott
<p>
This is bad information.
</p>
<p>
The expression
</p>
<code>
$expression ? $var = "foo" : $var = "bar";
</code>
<p>
is only <em>"<c># WRONG</c>"</em> because of operator precedence (see [http://perldoc.perl.org/perlop.html#Operator-Precedence-and-Associativity|perlop: Operator Precedence and Associativity]). Here's how it is parsed:
</p>
<code>
$ perl -MO=Deparse,-p -e '$expression ? $var = "foo" : $var = "bar";'
(($expression ? ($var = 'foo') : $var) = 'bar');
-e syntax OK
</code>
<p>
This is explained in [http://perldoc.perl.org/perlop.html#Conditional-Operator|perlop: Conditional Operator].
Correcting the precedence with parentheses:
</p>
<code>
$ perl -MO=Deparse,-p -e '$expression ? ($var = "foo") : ($var = "bar");'
($expression ? ($var = 'foo') : ($var = 'bar'));
-e syntax OK
</code>
<p>
<strong>I do not dispute that '<c>$var = $expression ? "foo" : "bar";</c>' is a better way to write '<c>$expression ? ($var = "foo") : ($var = "bar");</c>'.</strong>
In fact, the documentation also recommends this.
</p>
<p>
Once corrected as indicated, here's how your <em>"<c># WRONG</c>"</em> code behaves:
</p>
<code>
#!/usr/bin/env perl -l
use strict;
use warnings;
for my $expression (0, 1) {
my $var = '';
$expression ? ($var = 'foo') : ($var = 'bar');
print "\$expression = '$expression'; \$var = '$var'";
}
</code>
<p>Output:</p>
<code>
$expression = '0'; $var = 'bar'
$expression = '1'; $var = 'foo'
</code>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-861371">
<p>-- Ken</p>
</div></div>
1067306
1067329