为什么 !1 在 Perl 中什么也没给我? [英] Why does !1 give me nothing in Perl?

查看:28
本文介绍了为什么 !1 在 Perl 中什么也没给我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很奇怪.以下:

$sum = !0;
print $sum;

如您所料打印出 1.但是这个

prints out 1 as you would expect. But this

$sum = !1;
print $sum;

什么都不打印.为什么?

prints out nothing. Why?

推荐答案

请注意:您所写的内容并非您认为的那样.请记住,perl 没有真正的布尔数据类型.它有标量、散列、列表和引用.然后,它处理真/假值的方式是上下文相关的.在 perl 中,除了未定义的变量、空列表、空字符串和数字 0 外,所有内容都评估为真".

Be careful: what you've written isn't doing what you think it's doing. Remember, perl has no real boolean datatype. It's got scalars, hashes, lists, and references. The way it handles true/false values, then, is contextual. Everything evaluates to "true" in perl except for undefined variables, the empty list, the empty string, and the number 0.

那么,您的代码正在执行的操作是取求值为false"的值的倒数,该值可以是上面列表中没有的任何值.按照惯例,为了简单起见,perl 返回 1(尽管您不应该依赖它;它很可能返回一个包含一系列随机数的列表,因为它也会评估为真".)

What your code is doing, then, is taking the inverse of a value that evaluates to "false", which can be anything which is not in the list above. By convention and for simplicity's sake, perl returns 1 (though you should not rely on that; it could very well return a list containing a series of random numbers, because that will evaluate to "true" as well.)

当您要求求值为真"的值的倒数时,会发生类似的事情.实际打印出来的不是什么都没有",而是空字符串 (''),正如我提到的,它在布尔表达式中的计算结果为false".你可以检查一下:

A similar thing happens when you ask for the inverse of a value that evaluates to "true." What's actually being printed out is not "nothing," it's the empty string (''), which, as I mentioned, evaluates to "false" in boolean expressions. You can check this:

print "This evaluates to false
" if( (!1) eq '');

如果您要问为什么 perl 吐出空字符串而不是其他假"值之一,那么,可能是因为 perl 是用来处理字符串的,而这是一个完全合理的字符串,可以交还.

If you're asking for why perl spits out the empty string instead of one of the other "false" values, well, it's probably because perl is made to handle strings and that's a perfectly reasonable string to hand back.

这篇关于为什么 !1 在 Perl 中什么也没给我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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