为什么 Perl 认为 -1 为真?
这是一段常见的示例代码:
while (1) {
print "foo\n";
}
它永远打印“foo”。
perl foo.pl
foo
foo
foo
...
并
while (0) { print "foo\n"; }
如您所愿静静地死去:
perl test.pl
有人能解释为什么这是 while 的一个有用的实现吗?这至少适用于 5.10、Unix 和 MacOS X
while (-1) { print "foo\n"; }
:
foo
foo
foo
...
This is a piece of common example code:
while (1) {
print "foo\n";
}
which prints 'foo' forever.
perl foo.pl
foo
foo
foo
...
and
while (0) { print "foo\n"; }
dies quietly as you expect:
perl test.pl
Can someone explain why this is a useful implementation of while? This works on 5.10 at least, Unix and MacOS X:
while (-1) { print "foo\n"; }
which gives
foo
foo
foo
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
每个非零整数的计算结果都是
true
。 0 总是假
Every non-zero integer evaluates to
true
. And 0 is alwaysfalse
如果有的话,可以说
-1
比1
更有可能为真,因为-1
(111..111b
code>) 是零的按位求反 (000..000b
)。 BASIC 和 GW-BASIC 在需要返回真值时使用 -1。无论如何,Perl 认为表示“空”或“无”的值是错误的。大多数语言都持有类似的观点。具体来说,整数零、浮点零、字符串零、空字符串和 undef 为 false。
这是记录,尽管文档措辞不佳。 (它将
()
列为 false 值,但没有这样的值。)除了一致性之外,采用这种方法非常有用。例如,它允许人们使用
而不是
If anything, one could say
-1
is more likely to be true than1
since-1
(111..111b
) is the bitwise negation of zero (000..000b
). BASIC and GW-BASIC used -1 when they needed to return a true value.Regardless, Perl decided that values that mean "empty" or "nothing" are false. Most languages take a similar view. Specifically, integer zero, floating point zero, the string zero, the empty string and undef are false.
This is documented, although the documentation is poorly worded. (It lists
()
as a value that's false, but there is no such value.)Aside from consistency, it's very useful to take this approach. For example, it allows one to use
instead of
来自perldoc perlsyn(真相与谎言):
-1
被认为是 true。From perldoc perlsyn (Truth and Falsehood):
-1
is considered true.问题是“为什么 perl 认为 -1 是真的?”。。
答案是当 Perl 开发时,决定某些值将评估为 false。这些是:
这就是我能想到的关于原因的合适答案。它就是这样设计的。
The question is 'why does perl think -1 is true?'.
The answer is when perl was developed it was decided that certain values would evaluate to false. These are:
That is all I can think of a a suitable answer as to why. It was just designed that way.
只有 0 整数才被视为 false。任何其他非零整数都被视为 true。
Only a 0 integer is considered false. Any other non-zero integer is considered true.
任意整数<> 0 为真。
0 始终为假。
any integer <> 0 is true.
0 is always false.
Perl 从
awk
和C
继承了这种行为。这里解释了为什么
C
这样做。Perl took this behavior from
awk
andC
.Why
C
does it is explained here.