游.程 2008-08-15 19:43 采纳率: 0%
浏览 144
已采纳

如何判断变量在 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))
{ ... }

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

转载于:https://stackoverflow.com/questions/12647/how-do-i-tell-if-a-variable-has-a-numeric-value-in-perl

  • 写回答

14条回答 默认 最新

  • 谁还没个明天 2008-08-26 16:53
    关注

    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.

    Example:

    #!/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\n";
    }
    

    Gives this output:

    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
    

    see also:

    [perldoc Scalar::Util][1]
    [perldoc perlapi][2] 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(13条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大