在perl中将数字视为数字的最简单方法?
我有一个条件:
next if ( ! ($x or $y or $z) );
检查的逻辑是至少有一个必须在数值上非零才能继续循环。
我相信它们实际上是数字。
问题是 Perl 在内部将浮点数存储为字符串。所以检查! $x
其中 $x='0.00'
实际上并不计算为 true: my $x = 0.00;
if ( ! $x ) { never_gets_here(); }
强制对变量进行数值计算而不使该行过于冗长的最简单方法是什么?
I have a condition:
next if ( ! ($x or $y or $z) );
The logic of the check is that at least one must be numerically non-zero to continue in the loop.
I trust that they actually are numbers.
The problem is that perl stores floats as strings internally. So a check on ! $x
where $x='0.00'
does not actually evaluate to true: my $x = 0.00;
if ( ! $x ) { never_gets_here(); }
What is the easiest way to force numeric evaluation of a variable without making the line too verbose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不确定你从哪里得到 Perl 将浮点数存储为字符串的想法。浮点数和字符串是不同的东西:
如果你想在未知标量上强制数字上下文,你可以只向它添加零,例如
I'm not sure where you get the idea that Perl stores floats as strings. Floats and strings are different things:
If you want to force numeric context on an unknown scalar, you can just add zero to it, e.g.
如果你想检查一个数字是否非零,可以使用一个运算符:
If you want to check whether a number is numerically non-zero, there is an operator for that:
要检查数字是否具有非零值,您只需添加 0:
,
这在 Perl 中是假值:
To check if number has non-zero value you can just add 0:
and
which is falsy value in Perl:
将零 (0) 添加到变量(就像在“awk”中一样)。
Add zero (0) to the variable (just as you would in 'awk').
如果没有(或仅有)负值,您可以使用以下快捷方式,恕我直言,这比向每个单个值添加零更干净:
You could use following shortcut if there are no ( or exclusively ) negative values, which is imho cleaner than adding zero to each single value: