eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
I stumbled on some code at work today that caused me to pull a face:
Clearly the intent was:$fred == 42 ? $config = 'k1' : $config = 'k2';
my $config = $fred == 42 ? 'k1' : 'k2';
Yet I was surprised that the code compiled without a syntax error. The following test program illustrates:
Running:# 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";
produces:perl weird1.pl 42
Running:fred='42' config='k2'
produces:perl weird1.pl 69
That is, $config is always set to k2. Can anyone explain what is going on? That is, how is Perl parsing:fred='69' config='k2'
Running this line of code through MO=Deparse produced the same output.$fred == 42 ? $config = 'k1' : $config = 'k2';
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Surprised by Perl parse of ternary operator
by BrowserUk (Patriarch) on Dec 16, 2011 at 08:14 UTC | |
|
Re: Surprised by Perl parse of ternary operator
by bart (Canon) on Dec 16, 2011 at 11:22 UTC | |
by moritz (Cardinal) on Dec 16, 2011 at 12:50 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 16, 2011 at 12:52 UTC | |
by BrowserUk (Patriarch) on Dec 16, 2011 at 13:18 UTC | |
by Anonymous Monk on Dec 16, 2011 at 15:32 UTC | |
by tye (Sage) on Dec 16, 2011 at 14:53 UTC | |
by wrog (Friar) on Jan 16, 2012 at 00:27 UTC | |
by tye (Sage) on Jan 16, 2012 at 04:32 UTC |