Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Surprised by Perl parse of ternary operator

by bart (Canon)
on Dec 16, 2011 at 11:22 UTC ( #943930=note: print w/ replies, xml ) Need Help??


in reply to Surprised by Perl parse of ternary operator

It is indeed a bit weird since ?: has higher precedence than =: respective precedence levels 18 and 19, see Operator Precedence and Associativity.

I guess that the perl parser is a bit of a smart-ass here, as bending the precedence rules a little will allow the expression to get successfully parsed, instead of producing an unhelpful syntax error.


Comment on Re: Surprised by Perl parse of ternary operator
Select or Download Code
Re^2: Surprised by Perl parse of ternary operator
by moritz (Cardinal) on Dec 16, 2011 at 12:50 UTC
    It is indeed a bit weird since ?: has higher precedence than =

    If it were any different, the useful idiom

    my $x = $condition ? $a : $b;

    would be parsed as

    (my $x = $condition) ? $a : $b

    which totally wouldn't make sense. It's useful to optimize the operator precedence level for idiomatic use, not for misunderstood corner cases.

    That said, it is possible to both allow the common case and detect the error; that's what Perl 6 does:

    # program (note that Perl 6 uses ??!! instead of ?:) 1 ?? $_ = 3 !! $_ = 5 # output from the Perl 6 standard grammar: Precedence of = is too loose to use between ?? and !!; please use pare +ns around inner expression at ...

    But I guess Perl 5 won't do it soon, because it'll break some obfuscations that successfully "use" that feature somewhere.

Re^2: Surprised by Perl parse of ternary operator
by eyepopslikeamosquito (Canon) on Dec 16, 2011 at 12:52 UTC

    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:

    config = '' fred = 42 fred == 42 ? config = 'k1' : config = 'k2' print "config=#{config}\n"
    and PHP program:
    <?php $config = ''; $fred = 42; $fred == 42 ? $config = 'k1' : $config = 'k2'; echo "config=$config\n"; ?>
    both run without error, but, unlike Perl (which produces config=k2), both Ruby and PHP produce config=k1.

    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):

    #include <stdio.h> int main() { int config = 0; int fred = 42; fred == 42 ? config = 1 : config = 2; printf("config=%d\n", config); return 0; }
    Adding parentheses to line 6:
    fred == 42 ? (config = 1) : (config = 2); // this works fred == 42 ? config = 1 : (config = 2); // also works fred == 42 ? (config = 1) : config = 2; // syntax error
    makes it work the same as the Ruby and PHP test programs.

      bend the rules differently.

      I wouldn't exactly call it "bending the rules". For perl or the other two.

      I read it that perl uses a minimal munch approach at that point of the syntax and hence sees:

      ( ( $fred == 42) ? ( $config = 'k1') : ( $config ) ) = 'k2';

      Whereas the other two use a maximal munch approach and so see:

      ( $fred == 42 ) ? ( $config = 'k1' ) : ( $config = 'k2' );

      I think the use case for Perl's way is using the ternary as the lvalue target of assignment. Something like:

      $lo = $hi = 0; $x = 7; $mid = 5; $x < $mid ? $lo : $hi = $x; print "lo:$lo hi:$hi";; lo:0 hi:7

      Can Ruby or PHP do that?


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

      The start of some sanity?

        Can Ruby or PHP do that?

        No, at least Ruby seems to lack a concept of a "variable" lvalue. (foo = bar) = 5 gives a syntax error, and x < mid ? lo : hi = x gets parsed as x < mid ? lo : (hi = x)

      Are you unfamiliar with how an LALR(1) grammar is parsed? (No, I don't know if Perl strictly constitutes an LALR(1) grammar, but it does use yacc / bison and so at least much of the parsing actually follows the LALR(1) rules.)

      Your conclusion would only be correct if both PHP and Ruby behaved the same for the equivalent of Perl's:

      ( $config = 'k1' ) = 'k2';

      which I couldn't even get PHP to compile (no Ruby handy).

      If you think Perl is bending some rules, then please point out the rule-bending code that it gives to yacc / bison. The fact is that declared precedence only comes into play when a "shift/reduce conflict" is found in generating the parser state machine.

      What I see is simply:

      %right <i_tkval> ASSIGNOP %right <i_tkval> '?' ':' ... termbinop: term ASSIGNOP term /* $x = $y */ ... | term '?' term ':' term

      Perl could make the grammar definition more complicated by not using yacc / bison declared precedence to implement the precedence of just the one ternary operator since it is the only case where there is a "middle argument" where declared precedence doesn't matter. But that would involve specifying yet another primitive for "expression" and having to pick the right one to use in each of the dozens of places where the current 'term' is used.

      I find it very Perlish that ?: precedence is enforced by declared precedence, not proscriptive grammar definition.

      (Updated: to add the relevant bits from perly.y)

      - tye        

        if I remember correctly, perl does not use LALR (yacc/bison) parsing but rather uses a Pratt-style precedence parser which is a kind of recursive descent but in which each operator is assigned a distinct left and right precedence...

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://943930]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2014-12-20 10:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls