Why is 'print (52-80)*42' different than 'print 42*(52-80)' in Perl?

后端 未结 3 597
说谎
说谎 2020-12-11 09:48

Perl:: What is:

1. (52-80)*42
2. 42*(52-80)

Ans:

1. -28
2. -1176

Why?

Have fun

相关标签:
3条回答
  • 2020-12-11 10:20

    If you add use warnings; you'll get:

    print (...) interpreted as function at ./test.pl line 5.
    Useless use of a constant in void context at ./test.pl line 5
    
    0 讨论(0)
  • 2020-12-11 10:27

    The warning that Alex Howansky aludes to means that

    print (52-80)*42 , "\n"
    

    is parsed as

    (print(52-80)) * 42, "\n"
    

    which is to say, a list containing (1) 42 times the result of the function print(-28), and (2) a string containing the newline. The side-effect of (1) is to print the value -28 (without a newline) to standard output.

    If you need to print an expression that begins with parentheses, a workaround is to prepend it with +:

    print +(52-80)*42, "\n"         #  ==> -1176
    
    0 讨论(0)
  • 2020-12-11 10:40

    Thanks to Perl's wacky parsing rules (oh Perl, you kook!), these statements:

    print ((52-80)*42) , "\n";
    print (52-80)*42 , "\n";
    

    Are interpreted as if they were written:

    (print ((52-80)*42)), "\n";
    (print (52-80))*42, "\n";
    

    This is why you end up seeing -1176-28 on one line, and the expected blank line is missing. Perl sees (print-expr), "\n"; and simply throws away the newline instead of printing it.

    0 讨论(0)
提交回复
热议问题