Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Surprised by Perl parse of ternary operator

by eyepopslikeamosquito (Canon)
on Dec 16, 2011 at 08:02 UTC ( #943895=perlquestion: print w/ replies, xml ) Need Help??
eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:

I stumbled on some code at work today that caused me to pull a face:

$fred == 42 ? $config = 'k1' : $config = 'k2';
Clearly the intent was:
my $config = $fred == 42 ? 'k1' : 'k2';

Yet I was surprised that the code compiled without a syntax error. The following test program illustrates:

# weird1.pl use strict; use warnings; my $config; my $fred = shift; print "fred='$fred'\n"; $fred == 42 ? $config = 'k1' : $config = 'k2'; print "config='$config'\n";
Running:
perl weird1.pl 42
produces:
fred='42' config='k2'
Running:
perl weird1.pl 69
produces:
fred='69' config='k2'
That is, $config is always set to k2. Can anyone explain what is going on? That is, how is Perl parsing:
$fred == 42 ? $config = 'k1' : $config = 'k2';
Running this line of code through MO=Deparse produced the same output.

Comment on Surprised by Perl parse of ternary operator
Select or Download Code
Re: Surprised by Perl parse of ternary operator
by BrowserUk (Pope) on Dec 16, 2011 at 08:14 UTC
    Running this line of code through MO=Deparse produced the same output.

    Add -p to show the precedence:

    c:\test>perl -MO=Deparse,-p -e"$fred == 42 ? $config = 'k1' : $config += 'k2';" ((($fred == 42) ? ($config = 'k1') : $config) = 'k2'); -e syntax OK

    (And yes. It's weird :)


    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?

Re: Surprised by Perl parse of ternary operator
by bart (Canon) on Dec 16, 2011 at 11:22 UTC
    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.

      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.

      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?

        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        

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://943895]
Approved by GrandFather
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (9)
As of 2014-12-26 02:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (164 votes), past polls