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

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

提交回复
热议问题