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

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

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

提交回复
热议问题