in reply to Ternary if versus normal if question

Run the code with -MO=Deparse,-p, and the line with the ternary operator becomes:
(($lights{$light} ? ($lights{$light} = 0) : $lights{$light}) = 1);
You can see that the 2nd assignment operator has lower precedence than the ternary operator. So this says,
If $lights{$light} is true, then assign 1 to the result of "$lights{$light}=0", otherwise assign 1 to the result of $lights{$light}.
... which is not what you want. A better way to use the ternary here is:
$lights{$light} = $lights{$light} ? 0 : 1;
Or even better still is probably:
$lights{$light} = ! $lights{$light};
which toggles $lights{$light} between true & false.

blokhead

Replies are listed 'Best First'.
Re^2: Ternary if versus normal if question
by xdg (Monsignor) on Nov 17, 2005 at 14:08 UTC

    Also, the docs for B::Deparse around the -xLEVEL option pretty much implies that ternaries and ifs are equivalent:

    If *LEVEL* is at least 7, "if" statements will be translated into equivalent expressions using "&&", "?:" and "do {}"; for instance print 'hi' if $nice; if ($nice) { print 'hi'; } if ($nice) { print 'hi'; } else { print 'bye'; } turns into $nice and print 'hi'; $nice and do { print 'hi' }; $nice ? do { print 'hi' } : do { print 'bye' };

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.