What is wrong with print (2 & 2) >> 1?

假如想象 提交于 2020-03-03 10:00:07

问题


I am just wondering what happens with that piece of code. Why the result is incorrect only when printed directly, why is the newline ignored?

user@host_09:22 AM: perl
print 2 >> 1, "\n";
print 2 & 2, "\n";
print (2 & 2) >> 1, "\n";
1
2
2user@host_09:22 AM: perl
$a = (2 & 2) >> 1;
print "$a\n";
1

回答1:


When you print it with warnings it becomes clear(er)

perl -we'print (2 & 2), "\n"'

says

print (...) interpreted as function at -e line 1.
Useless use of a constant ("\n") in void context at -e line 1.

It works out print (2&2) as a function call to print and duly prints 2 (no newline!), and then it keeps evaluating the comma operator, with "\n" in void context next, which it also warns us about.

With >> 1 also there, the return 1 of print (2&2) (for success) is bit shifted to 0, which disappears into the void, and we get another "Useless use of ... in void context."

One fix is to add a + since what follows it must be an expression

perl -we'print +(2 & 2) >> 1, "\n"'

Or, make a proper call to print, with parenthesis around the whole thing

perl -we'print((2 & 2) >> 1, "\n")'

Both print a line with 1.

This is mentioned in print, and more fully documented in Terms and List operators and in Symbolic Unary operators, both in perlop.


 It also warns about it as it is likely an error -- with a space before parens; no space, no warning.




回答2:


Perl interprets the parentheses as function arguments marker, as you can verify with

perl -MO=Deparse,-p -e 'print (2 & 2) >> 1'

Output:

(print(2) >> 1);

The canonical way is to precede the left parenthesis with a +:

print +(2 & 2) >> 1


来源:https://stackoverflow.com/questions/56556804/what-is-wrong-with-print-2-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!