除非-和“如果!”的不同行为是如何产生的?语句影响标量上下文中的范围运算符?
在 http://novosial.org/perl/one-liner/ 上我发现了以下内容两个单行线。输出不同,因为 unless
语句与 if !
不同(由于关联性和优先级规则)。
cat file: foo bar
perl -ne 'print unless /^$/../^$/' file foo bar
perl -ne 'print if ! /^$/../^$/' file foo bar
if !
语句的不同行为如何使第二个单行输出一个空行?
On http://novosial.org/perl/one-liner/ I found the following two one-liners. The outputs are different because the unless
statement is different from if !
( due to the associativity and precedence rules ).
cat file: foo bar
perl -ne 'print unless /^$/../^$/' file foo bar
perl -ne 'print if ! /^$/../^$/' file foo bar
How does the different behavior of the if !
-statement make the second one-liner output one blank line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如链接的文章所述,这是关联性和优先级的问题...
print except /^$/../^$/
相当于print if !(/^$/. ./^$/)
打印如果! /^$/../^$/
相当于print if (!/^$/)../^$/
请注意,第一个否定范围表达式,而第二个否定范围的开始条件,但不否定范围本身。
As the linked article says, it's a matter of associativity and precedence...
print unless /^$/../^$/
is equivalent toprint if !(/^$/../^$/)
print if ! /^$/../^$/
is equivalent toprint if (!/^$/)../^$/
Note that the first negates the range expression, while the second negates the range's beginning condition, but not the range itself.
恕我直言,答案是 Perl 中没有
if !
语句:有一个if
语句,并且有一个!
运算符。!
运算符不绑定到if
;它根据它的论点运作。如果你开始从这些角度思考,你的生活会更轻松。因此,在您的情况下,您有,
并且
让我们放入通常不可见的括号中:
并且
在这种情况下,您尝试编写
something-else
以便该条件的真值等于真值something
,但未能考虑到!
运算符紧密绑定的事实。这就是为什么
没有
。尝试
在 perldoc perlop 中查看
not
:The answer, IMHO, is that there is no
if !
statement in Perl: There is anif
statement and there is a!
operator. The!
operator does not bind toif
; it operates on its argument. If you start thinking in these terms, your life will be easier.So, in your case, you have,
and
Let's put in the normally invisible parentheses:
and
In this case, you tried to write
something-else
so that the truth value of that condition is equivalent to the truth ofsomething
, but failed to take into account the fact that!
operator binds tightly.That is why there is
not
.Try
See
not
in perldoc perlop:范围测试将在第二个操作数为 true 之前返回 true。然后它将在下一次调用时返回 false。
这个片段告诉我们范围运算符返回什么
,它会产生
第一个空行生成一个 true 响应,下一个空行生成 false
The range test will return true up to the time that the 2nd operand is true. It will then return false on the next call.
This snippet tells us what the range operator is returning
which produces
So the first blank line generates a true response, the next one false