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

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

    Personally I think that the way to go is to rely on Perl's internal context to make the solution bullet-proof. A good regexp could match all the valid numeric values and none of the non-numeric ones (or vice versa), but as there is a way of employing the same logic the interpreter is using it should be safer to rely on that directly.

    As I tend to run my scripts with -w, I had to combine the idea of comparing the result of "value plus zero" to the original value with the no warnings based approach of @ysth:

    do { 
        no warnings "numeric";
        if ($x + 0 ne $x) { return "not numeric"; } else { return "numeric"; }
    }
    

提交回复
热议问题