in reply to Re^2: How to check Inputs if Numeric
in thread How to check Inputs if Numeric

This question was actually from me. Something went wrong with my login and my login was not recorded.

Replies are listed 'Best First'.
Re^4: How to check Inputs if Numeric
by Athanasius (Archbishop) on Aug 29, 2014 at 14:12 UTC

    Hello carolw,

    To check if a variable is a positive integer, do you recommend to use Scalar::Util::LooksLikeNumber ... ?

    I assume you mean Scalar::Util::looks_like_number, but that won’t distinguish between positive integers and other types of numbers, such as floating-point numbers and negative integers.

    It’s possible that the simple regex /^\+?\d+$/ is all you need, but that won’t recognise positive integers such as 0xDEADBEEF and 1e6. For a comprehensive solution, the Data::Types module has the is_whole function:

    use strict; use warnings; use Data::Types ':whole'; for (0, -1, 17, 1.25, 1e6, 062, 0xDEADBEEF, 4.0, 5.) { printf "%10s: %s\n", $_, is_whole($_) ? 'yes' : 'no'; }

    Output:

    23:51 >perl 989_SoPW.pl 0: yes -1: no 17: yes 1.25: no 1000000: yes 50: yes 3735928559: yes 4: yes 5: yes 23:51 >

    For additional options, see How-do-I-determine-whether-a-scalar-is-a-number-whole-integer-float of perlfaq4 cited by bronto further down in this thread.

    Something went wrong with my login and my login was not recorded.

    From the Settings Nodelet, go to Display Settings and change the Theme Container to, say, the “Red Theme.” You will then have an unmistakable visual cue as to whether or not you are logged in to PerlMonks.

    Update 1: Escaped the first + in the regex:

    /^\+?\d+$/ ^

    Update 2: Actually, the simple regex does recognise 0xDEADBEEF and 1e6 because Perl converts them to standard decimal form before the regex is applied.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,