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

前端 未结 14 1356
别那么骄傲
别那么骄傲 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.

    0 讨论(0)
  • 2020-11-28 07:39

    I found this interesting though

    if ( $value + 0 eq $value) {
        # A number
        push @args, $value;
    } else {
        # A string
        push @args, "'$value'";
    }
    
    0 讨论(0)
提交回复
热议问题