在 Perl 中,如何判断变量是否具有数值?

编程入门 行业动态 更新时间:2024-10-27 20:38:03
本文介绍了在 Perl 中,如何判断变量是否具有数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Perl 中是否有一种简单的方法可以让我确定给定的变量是否为数字?类似的东西:

Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:

if (is_number($x)) { ... }

会是理想的.在使用 -w 开关时不会抛出警告的技术当然是首选.

would be ideal. A technique that won't throw warnings when the -w switch is being used is certainly preferred.

推荐答案

Use Scalar::Util::looks_like_number() 它使用内部 Perl C API 的 look_like_number() 函数,这可能是最有效的方法来做到这一点.请注意,字符串inf"和infinity"被视为数字.

Use Scalar::Util::looks_like_number() which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this. Note that the strings "inf" and "infinity" are treated as numbers.

#!/usr/bin/perl use warnings; use strict; use Scalar::Util qw(looks_like_number); my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity); foreach my $expr (@exprs) { print "$expr is", looks_like_number($expr) ? '' : ' not', " a number "; }

给出这个输出:

1 is a number 5.25 is a number 0.001 is a number 1.3e8 is a number foo is not a number bar is not a number 1dd is not a number inf is a number infinity is a number

另见:

  • perldoc 标量::Util
  • perldoc perlapi looks_like_number

更多推荐

在 Perl 中,如何判断变量是否具有数值?

本文发布于:2023-07-26 09:36:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1215532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数值   变量   如何判断   Perl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!