in reply to Re: Surprised by Perl parse of ternary operator
in thread Surprised by Perl parse of ternary operator
Curiously, both Ruby and PHP, both with the same relative precedence as Perl for the ternary and assignment operators, bend the rules differently. For example, this Ruby program:
and PHP program:config = '' fred = 42 fred == 42 ? config = 'k1' : config = 'k2' print "config=#{config}\n"
both run without error, but, unlike Perl (which produces config=k2), both Ruby and PHP produce config=k1.<?php $config = ''; $fred = 42; $fred == 42 ? $config = 'k1' : $config = 'k2'; echo "config=$config\n"; ?>
Arguably, all three languages should produce a syntax error.
Update: gcc produces a syntax error "f.c:6: error: lvalue required as left operand of assignment" with this test program (further update: g++ compiles it happily though and with the same semantics as the Ruby and PHP test programs):
Adding parentheses to line 6:#include <stdio.h> int main() { int config = 0; int fred = 42; fred == 42 ? config = 1 : config = 2; printf("config=%d\n", config); return 0; }
makes it work the same as the Ruby and PHP test programs.fred == 42 ? (config = 1) : (config = 2); // this works fred == 42 ? config = 1 : (config = 2); // also works fred == 42 ? (config = 1) : config = 2; // syntax error
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Surprised by Perl parse of ternary operator
by BrowserUk (Patriarch) on Dec 16, 2011 at 13:18 UTC | |
by Anonymous Monk on Dec 16, 2011 at 15:32 UTC | |
|
Re^3: Surprised by Perl parse of ternary operator (parsing)
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 |