print(2& 2)>>怎么了? 1个? [英] What is wrong with print (2 & 2) >> 1?

查看:74
本文介绍了print(2& 2)>>怎么了? 1个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道这段代码会发生什么. 为什么只在直接打印时结果不正确,为什么换行符会被忽略?

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

推荐答案

在打印带有警告的内容时,它会变得很清晰(er)

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

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


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

它将print (2&2)作为对print 的函数调用,并正确打印2(没有换行符!),然后继续评估,它也警告我们.

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.

同时还有>> 1print (2&2)的返回1(成功)已移至0,它消失在空白中,我们得到 另一个"在无效上下文中对...的无用使用."

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"'

或者,适当地调用print,并在整个内容中加上括号

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

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

都用1打印一行.

打印中已提及,并在术语和列表运算符这篇文章.

This is mentioned in print, and more fully documented in Terms and List operators and in Symbolic Unary operators, both in perlop. For another, related, example see this post.

 还警告它,因为这很可能是错误的-在括号前留一个空格;没有空间,没有警告.

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

这篇关于print(2& 2)>>怎么了? 1个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆