打印和三元条件运算符之间的奇怪交互 [英] Strange interaction between print and the ternary conditional operator

查看:57
本文介绍了打印和三元条件运算符之间的奇怪交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print 和我不理解的三元条件运算符之间进行了奇怪的交互.如果我们这样做...:

Ran into a strange interaction between print and the ternary conditional operator that I don't understand. If we do...:

打印'foo,'.(1吗?是":否").'bar';

...然后我们得到输出...:

...then we get the output...:

foo,是的吧

...正如我们所期望的.但是,如果这样做...:

...as we would expect. However, if we do...:

print(1?'yes':'no').'bar';

...然后我们只得到输出...:

...then we just get the output...:

在第二种情况下,为什么不将"bar"附加到输出中?

Why isn't " bar" getting appended to the output in the second case?

推荐答案

让我们这样做,但实际上是警告

Let's do it, but for real -- that is, with warnings on

perl -we'print (1 ? "yes" : "no") . " bar"'

它打印


print (...) interpreted as function at -e line 1.
Useless use of concatenation (.) or string in void context at -e line 1.
yes

(但末尾没有换行符)

因此,由于(1?"yes":"no")被用作 print 函数的参数列表,因此三元被评估为 yes ,并且这是 print 的参数,因此可以单独打印.由于这是一个已知的陷阱",很容易出错,因此我们对此给予警告.

So since (1 ? "yes" : "no") is taken as the argument list for the print function then the ternary is evaluated to yes and that is the argument for print and so that, alone, is printed. As this is a known "gotcha," which can easily be done in error, we are kindly given a warning for it.

然后将字符串"bar" 连接(连接到 print 的返回值,即 1 ),这在void上下文中是没有意义的,同时我们也会收到警告.

Then the string " bar" is concatenated (to the return value of print which is 1), what is meaningless in void context, and for what we also get a warning.

一种解决方法是在 + 之前添加前缀,强制将()解释为表达式

One workaround is to prepend a +, forcing the interpretation of () as an expression

perl -we'print +(1 ? "yes" : "no") . " bar", "\n"'

或者,使用完整的括号正确调用 print 作为函数

Or, call the print as function properly, with full parenthesis

perl -we'print( (1 ? "yes" : "no") . " bar", "\n" )'

在两种情况下我都添加了换行符.

where I've added the newline in both cases.

有关相关示例和精确文档链接的详细讨论,请参见这篇文章.

See this post for a detailed discussion of a related example and precise documentation links.

这篇关于打印和三元条件运算符之间的奇怪交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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