in reply to Question about ternary operator

The problem is that the assignment has a looser precedence than the ternary op. See also: perlop, Confused by Perl ternary operator, ternary operator. Why does the Perl conditional operator not do what I expect? and many other threads.

Replies are listed 'Best First'.
Re^2: Question about ternary operator
by merlinX (Novice) on Jul 01, 2009 at 08:42 UTC
    Thx, operator precedence is sometimes a PITA, so this is what the first ternary statement should look like then
    exists($checked->{Group}{$GroupDN}) ? ($rc_OK=1) : ($rc_OK=check_group +($GroupDN,0));
      No, it should look exactly like the first statement. The ternary operator is very good if you use its value, but if you use it in void context it's just a kludge for an if statement. So
      # bad: ternary in void context: exists($checked->{Group}{$GroupDN}) ? ($rc_OK=1) : ($rc_OK=check_group +($GroupDN,0)); # good: 'if' in void context: if (exists($checked->{Group}{$GroupDN})) { $rc_OK = 1 } else { $rc_OK=check_group($GroupDN,0) } # also good: ternary in scalar context: $rc_OK = exists($checked->{Group}{$GroupDN}) ? 1 : check_group($Group +DN,0)

      So you have two good, idiomatic ways to express something, and complain that the third is a PITA?

      Thx, operator precedence is sometimes a PITA

      If the precedence was reversed, the intended use would not work.

      $y = $c ? $x1 : $x2;
      would mean
      ($y = $c) ? $x1 : $x2;

      By the way, it's called the "conditional operator". Perl has many ternary operators.

Re^2: Question about ternary operator
by rovf (Priest) on Jul 01, 2009 at 11:50 UTC
    The problem is that the assignment has a looser precedence than the ternary op.

    Shouldn't then the OP's program had reported a syntax error?

    -- 
    Ronald Fischer <ynnor@mm.st>
      No:
      $ perl -MO=Deparse,-p -e '1 ? $a = 3 : $b = 4' (($a = 3) = 4); -e syntax OK

      You see it is parsed, not just the way you'd naively expect it.