in reply to Weird ?: behavior

If you run that line through B::Deparse, you get:
$hour > 11 ? ($xm = 'pm') : $xm = 'am';
The ternary operator (?:) has a higher precendence than =. That's why it's getting parsed that way.

Anyway, IMO, the best way to write that would be:

$xm = $hour > 11 ? "pm" : "am";
No precendence problems, and it's clearer, to me. I like using ternary operators for assignment, not for executing arbitrary code. It's just a matter of personal preference, really, but in certain cases it'll keep you out of trouble. Like this one. :)

Replies are listed 'Best First'.
RE: Re: Weird ?: behavior
by turnstep (Parson) on Aug 08, 2000 at 23:02 UTC
    It might also be clearer to you like this:
    $xm = ($hour>11) ? "pm" : "am";
RE: Re: Weird ?: behavior
by tye (Sage) on Aug 08, 2000 at 23:18 UTC
    $hour > 11 ? ($xm = 'pm') : $xm = 'am';

    To make this a little clearer, this is the same as:

    if( $hour > 11 ) { ( $xm= 'pm' )= 'am'; } else { $xm= 'am'; }

    So $xm is always set to 'am'.

            - tye (but my friends call me "Tye")