℡Wang Yan 2008-08-15 19:43 采纳率: 100%
浏览 1081
已采纳

如何判断变量在 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

  • 写回答

15条回答 默认 最新

  • 妄徒之命 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] 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?