Ternary ?: is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned.
貌似是return the argument,于是乎脑子里突然闪过一个念头, 在前后都加上了括号...
后来偶然的一次机会在PerlChina上问过此问题,才发现原来C和Perl对于 :? 和 =的优先级定义是不同的。在C中,= 的优先级高于:?,而Perl中则正好相反。这直接导致了第一种情况对于语句的解释顺序与C截然不同。对于x ? a = 1 : a = 2;,你期望解释为x ? (a = 1) : (a = 2);,实际却解释成了另外一个形式。
因此教训就是,文档在解释 ?: 的时候说的很清楚 If the argument before the ? is true, the argument before the : is returned,重点在return。所以,:? 里面应该尽量写"表达式",而非"语句"。非要用语句,那么请加括号避免优先级问题。