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

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

    if ( defined $x && $x !~ m/\D/ ) {} or $x = 0 if ! $x; if ( $x !~ m/\D/) {}

    This is a slight variation on Veekay's answer but let me explain my reasoning for the change.

    Performing a regex on an undefined value will cause error spew and will cause the code to exit in many if not most environments. Testing if the value is defined or setting a default case like i did in the alternative example before running the expression will, at a minimum, save your error log.

提交回复
热议问题