Perl 在字符串上下文中的条件运算符 [英] Perl's conditional operator in string context
问题描述
让我们采用以下简约脚本:
Let's take the following minimalistic script:
#!/usr/bin/perl
#
# conditional_operator.pl
#
use strict;
print ( 1 ? "true" : "false" )." statement\n";
exit;
我希望输出总是真实的陈述".但是当我执行这个片段时,我看到...
I expect the output always to be "true statement". But when I execute this snippet, I see ...
deviolog@home:~/test$ perl conditional_operator.pl
true
" statement\n"
连接似乎被忽略了.
我的 perl 版本是 v5.14.2.我阅读了 perlop 手册关于条件运算符 并认为,字符串连接应该是可能.
My perl version is v5.14.2. I read the perlop manual about the conditional operator and think, a string concatenation should be possible.
有人可以解释这种行为吗?
Can somebody explain this behaviour?
推荐答案
Always include 使用警告;
在每个脚本的顶部.
Always include use warnings;
at the top of every script.
要获得您想要的行为,只需添加括号,以便使用整个参数而不是第一部分调用 print
:
To get your desired behavior, just add parenthesis so print
is called with the entire argument instead of just the first part:
print(( 1 ? "true" : "false" )." statement\n");
如果您打开了warnings
,您就会收到此警报:
If you'd had warnings
turned on, you would've gotten this alert:
Useless use of concatenation (.) or string in void context
您还可以通过以空白连接开头来避免不受欢迎的行为,或者您可以在括号前放置一个加号:
You can also avoid the undesired behavior by leading with a blank concatenation, or you could put a plus sign before the parenthesis:
print +( 1 ? "true" : "false" )." statement\n";
print ''.( 1 ? "true" : "false" )." statement\n";
这篇关于Perl 在字符串上下文中的条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!