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

前端 未结 14 1355
别那么骄傲
别那么骄傲 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:13

    Try this:

    If (($x !~ /\D/) && ($x ne "")) { ... }
    
    0 讨论(0)
  • 2020-11-28 07:14

    A simple (and maybe simplistic) answer to the question is the content of $x numeric is the following:

    if ($x  eq  $x+0) { .... }
    

    It does a textual comparison of the original $x with the $x converted to a numeric value.

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

    You can use Regular Expressions to determine if $foo is a number (or not).

    Take a look here: How do I determine whether a scalar is a number

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

    rexep not perfect... this is:

    use Try::Tiny;
    
    sub is_numeric {
      my ($x) = @_;
      my $numeric = 1;
      try {
        use warnings FATAL => qw/numeric/;
        0 + $x;
      }
      catch {
        $numeric = 0;
      };
      return $numeric;
    }
    
    0 讨论(0)
  • 2020-11-28 07:21

    The original question was how to tell if a variable was numeric, not if it "has a numeric value".

    There are a few operators that have separate modes of operation for numeric and string operands, where "numeric" means anything that was originally a number or was ever used in a numeric context (e.g. in $x = "123"; 0+$x, before the addition, $x is a string, afterwards it is considered numeric).

    One way to tell is this:

    if ( length( do { no warnings "numeric"; $x & "" } ) ) {
        print "$x is numeric\n";
    }
    

    If the bitwise feature is enabled, that makes & only a numeric operator and adds a separate string &. operator, you must disable it:

    if ( length( do { no if $] >= 5.022, "feature", "bitwise"; no warnings "numeric"; $x & "" } ) ) {
        print "$x is numeric\n";
    }
    

    (bitwise is available in perl 5.022 and above, and enabled by default if you use 5.028; or above.)

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

    Usually number validation is done with regular expressions. This code will determine if something is numeric as well as check for undefined variables as to not throw warnings:

    sub is_integer {
       defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
    }
    
    sub is_float {
       defined $_[0] && $_[0] =~ /^[+-]?\d+(\.\d+)?$/;
    }
    

    Here's some reading material you should look at.

    0 讨论(0)
提交回复
热议问题