Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Perl中的lt和gt不能用于比较实数?_Perl - Fatal编程技术网

为什么Perl中的lt和gt不能用于比较实数?

为什么Perl中的lt和gt不能用于比较实数?,perl,Perl,让我们检查以下perl代码 if ($a lt 0.00 or $a gt 100.000) { print "a must be between 0 and 100 \n"; exit 1 } exit 0 假设a等于5。上述代码将以失败状态退出,因为a不在0和100之间 只需将lt和gt分别替换为它们所代表的实际运算符和code>,即可得到预期的结果。用以9开头的数字替换100也将产生预期的结果 为什么Perl的比较运算符告诉我5不在0和100之间?lt和gt是字符串运算符

让我们检查以下perl代码

if ($a lt 0.00 or $a gt 100.000)
{
    print "a must be between 0 and 100 \n";
    exit 1
}
exit 0
假设a等于5。上述代码将以失败状态退出,因为a不在0和100之间

只需将
lt
gt
分别替换为它们所代表的实际运算符
和code>,即可得到预期的结果。用以9开头的数字替换100也将产生预期的结果


为什么Perl的比较运算符告诉我5不在0和100之间?

lt
gt
是字符串运算符,数字要使用普通的旧
。Perl在值上是多态的,因此在操作符上是单态的(不像python那样)。在Perl中,
lt
gt
操作符与
操作符不同。perl文档在rational operators下对此进行了详细说明,下面是从文档中提取的:

Binary "<" returns true if the left argument is numerically less than the right argument.
Binary ">" returns true if the left argument is numerically greater than the right argument.
Binary "<=" returns true if the left argument is numerically less than or equal to the right argument.
Binary ">=" returns true if the left argument is numerically greater than or equal to the right argument.
Binary "lt" returns true if the left argument is stringwise less than the right argument.
Binary "gt" returns true if the left argument is stringwise greater than the right argument.
Binary "le" returns true if the left argument is stringwise less than or equal to the right argument.
Binary "ge" returns true if the left argument is stringwise greater than or equal to the right argument.
如果左参数的数值大于右参数,
Binary“”返回true。
如果左参数在数值上大于或等于右参数,则二进制“=”返回true。
如果左参数的字符串长度小于右参数的字符串长度,则二进制“lt”返回true。
如果左参数大于右参数,则二进制“gt”返回true。
如果左参数的字符串小于或等于右参数,则二进制“le”返回true。
如果左参数在字符串上大于或等于右参数,则二进制“ge”返回true。

由于perl没有字符串对象和整数对象,perl必须猜测对象的上下文。perl能够知道您是在比较字符串还是整数的唯一方法是确保
lt
gt
的有理运算符强制将比较上下文作为sting,并确保将比较上下文的
运算符作为整数编辑标题,因为“预期结果”只是您的预期,这是错误的。您可能会被
测试
命令(在shell脚本中用作
[
..
]
)弄糊涂,该命令使用
-gt
-lt
进行数值比较。使用
$a
也是一个坏消息。除了单字符变量名一般来说不好之外,它在
perl
中也有一个特定的含义-它用于
排序
。记住它的一个简单方法是,所有名称以字母拼写的运算符(
eq
lt
cmp
等)都对字符串进行操作,而名称类似于数学符号的运算符(
==