当数值比较为假时,Perl 返回什么? [英] What does Perl return when a numeric comparison is false?

查看:57
本文介绍了当数值比较为假时,Perl 返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行此代码.让我感到困惑的是,为什么这种比较在 false 时不返回任何值.这是这些比较运算符的默认行为吗?

I am trying to execute this code. What puzzles me is why doesn't this comparison return any value when false. Is this the default behavior of these comparison operators?

my $output = (2 <= 1); 
print "value=$output";

比较运算符在逻辑检查失败时会返回 undef 吗?

Will a comparison operator return undef when its logical check fails?

推荐答案

关系运算符

返回 1 表示 true 和定义的空字符串的特殊版本, "" ,它算作零,但免于有关不正确数字转换的警告,就像 "0 but true" 一样.

return 1 for true and a special version of the defined empty string, "" , which counts as a zero but is exempt from warnings about improper numeric conversions, just as "0 but true" is.

你得到的值实际上是一个对偶变量.它具有单独的数字和字符串值(实际上不是空字符串的特殊版本).数值为 0,字符串值为空字符串.您使用了空字符串部分,但 0 仍然存在.您可以使用 Devel::Peek:

The value you get back is actually a dualvar. It has separate numeric and string values (not a special version of the empty string, really). The numeric value is 0 and the string value is the empty string. You used the string portion, which is empty, but the 0 is still there. You can look inside the variable records with Devel::Peek:

use Devel::Peek;
my $result = ( 1 == 2 );
Dump( $result );

在幕后的 SV(标量值)事物中,您可以看到 PV 中的字符串值和 IV 和 NV(整数和数值)中的数值:

In the SV (scalar value) thing behind the scenes, you see the string value in the PV and the numeric value in the IV And NV (the integer and numeric values):

SV = PVNV(0x7fe602802750) at 0x7fe603002e70
  REFCNT = 1
  FLAGS = (PADMY,IOK,NOK,POK,pIOK,pNOK,pPOK)
  IV = 0
  NV = 0
  PV = 0x7fe6026016b0 ""\0
  CUR = 0
  LEN = 16

还有其他类型的双变量.$! 错误变量有错误编号和错误文本,例如(我在 精通 Perl).这通常不是您需要担心的,因为 Perl 会根据上下文做正确的事情.

There are other sorts of dualvars too. The $! error variable has the error number and the error text, for instance (and I talk about that in Mastering Perl). This isn't something you normally have to worry about because Perl does the right thing for the context.

如果您总是想要一个数值,请在数字上下文中使用它:

If you always want a numeric value, use it in a numeric context:

my $numeric = 0 + $result;   # 0

您可以使用 Scalar::Utildualvar,您可以使用 isdual 检查标量是否为双变量.

You can create your own dualvars with Scalar::Util's dualvar, and you can check if a scalar is a dualvar with isdual.

use Scalar::Util qw(isdual);
my $result = ( 1 == 2 );
print isdual($result) ? "dualvar" : "Not dualvar";

如果您想检查您返回的值是否已定义(您说没有),您可以使用 定义.但是,定义了一个空字符串.如果您想检查它是否不是空字符串,您可以使用 length.当您拥有的值不可打印时,这些会有所帮助.

If you wanted to check that the value you got back was defined (you said it wasn't), you can check with defined. An empty string is defined, though. If you want to check that it's not the empty string, you can use length. These help when the value you have isn't printable.

这篇关于当数值比较为假时,Perl 返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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