I stumbled on some code at work today that caused me to pull a face:
$fred == 42 ? $config = 'k1' : $config = 'k2';
Clearly the intent was:
my $config = $fred == 42 ? 'k1' : 'k2';
Yet I was surprised that the code compiled without a syntax error.
The following test program illustrates:
# weird1.pl
use strict;
use warnings;
my $config;
my $fred = shift;
print "fred='$fred'\n";
$fred == 42 ? $config = 'k1' : $config = 'k2';
print "config='$config'\n";
Running:
perl weird1.pl 42
produces:
fred='42'
config='k2'
Running:
perl weird1.pl 69
produces:
fred='69'
config='k2'
That is,
$config is always set to
k2.
Can anyone explain what is going on?
That is, how is Perl parsing:
$fred == 42 ? $config = 'k1' : $config = 'k2';
Running this line of code through
MO=Deparse produced the same output.