How do I tell if a variable has a numeric value in Perl?

前端 未结 14 1414
别那么骄傲
别那么骄傲 2020-11-28 06:56

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))
{ ... }
         


        
14条回答
  •  感情败类
    2020-11-28 07:33

    A slightly more robust regex can be found in Regexp::Common.

    It sounds like you want to know if Perl thinks a variable is numeric. Here's a function that traps that warning:

    sub is_number{
      my $n = shift;
      my $ret = 1;
      $SIG{"__WARN__"} = sub {$ret = 0};
      eval { my $x = $n + 1 };
      return $ret
    }
    

    Another option is to turn off the warning locally:

    {
      no warnings "numeric"; # Ignore "isn't numeric" warning
      ...                    # Use a variable that might not be numeric
    }
    

    Note that non-numeric variables will be silently converted to 0, which is probably what you wanted anyway.

提交回复
热议问题