【问题标题】:Why do lt and gt in Perl not work for comparing real numbers?为什么 Perl 中的 lt 和 gt 不能用于比较实数?
【发布时间】:2015-11-10 21:12:20
【问题描述】:

让我们检查以下 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 之间。

只需将ltgt 分别替换为它们所代表的实际运算符<>,即可产生预期的结果。将 100 替换为以 9 开​​头的数字也会产生预期的结果。

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

【问题讨论】:

  • 编辑标题,因为“预期结果”只是您的期望,这是错误的。
  • 您可能对test 命令(在shell 脚本中用作[ ... ])感到困惑,该命令使用-gt-lt 进行数字比较。跨度>
  • 使用$a 也很糟糕。除了一般来说单字符变量名不好之外,它在perl 中也有特定含义 - 它用于sort

标签: perl


【解决方案1】:

ltgt 是字符串运算符,您希望使用普通的旧 <> 数字。 Perl 在值上是多态的,所以它在运算符上是单态的(不像 python 是相反的)。

【讨论】:

  • 一个容易记住的方法是,所有名称以字母拼写的运算符(eqltcmp 等)都对字符串进行操作,而名称看起来像数学符号(==<<=> 等)对数字进行运算。
【解决方案2】:

在 perl 中,ltgt 运算符与 <> 不同。 perl 文档在此perlop 在理性运算符下对此进行了详细说明,以下摘自文档:

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.

由于 perl 没有字符串对象和整数对象 perl 必须猜测对象的上下文。 perl 可以知道您是在比较字符串还是整数的唯一方法是确保 ltgt 的有理运算符将比较的上下文强制为字符串,并且 &lt;&gt; 运算符用于整数比较的上下文

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2017-05-14
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多