zerodata has asked for the wisdom of the Perl Monks concerning the following question:

I want to check the output of a mathematical function to check if it is an integer or a float So I can use it in an if funtion ie
if ($var == integer) { print "$a is an integer.\n"; } elsif ($var == float) { print "$a is a float.\n"; } else { print "$a is neither an integer or float.\n"; }
What I do not know how to do is check if the output is an integer a float or a string Any help greatly appreciated as I am new to perl and porogramming

Replies are listed 'Best First'.
Re: Is the number an Integer or a Float
by cjf-II (Monk) on Dec 08, 2002 at 00:25 UTC

    Using Data::Types:

    use Data::Types qw/:all/; my @numbers = (0, 3.14, 5); for my $num (@numbers) { if (is_int($num)) { print "$num is an int.\n"; } elsif (is_float($num)) { print "$num is a float.\n"; } else { print "$num is something else.\n"; } }

    That should print:

    0 is an int. 3.14 is a float. 5 is an int.

    More excellent examples in the docs

Re: comparing output to check if is an integer or float
by pg (Canon) on Dec 07, 2002 at 23:53 UTC
    Check perlfaq4, under Data:Misc, the second faq is how can you determine whether a string is an integer or float. As you said that you are new, I copied a piece from the answer, and pasted it here, hope it helps.

    It basically said two things:
    • You can do it by yourself, use regexp, and the regexp's you needed are listed below.
    • If you want call some module, there is a CPAN module.
    (As you said the entity you want to check is returned from some math function, maybe I can assume the return is a number. If that is true, you can just check whether int($num) == $num.)
    Assuming that you don't care about IEEE notations like ``NaN'' or ``In +finity'', you probably just want to use a regular expression. if (/\D/) { print "has nondigits\n" } if (/^\d+$/) { print "is a whole number\n" } if (/^-?\d+$/) { print "is an integer\n" } if (/^[+-]?\d+$/) { print "is a +/- integer\n" } if (/^-?\d+\.?\d*$/) { print "is a real number\n" } if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number\n" +} if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) { print "a C float\n" }You can also use the Da +ta::Types module on the CPAN, which exports functions that validate d +ata types using these and other
      The OP didnt actually say if the number in question was coming from an input stream of some sort or an internally generated one. If it was internally generated one then
      if (int($num)==$num) {
      would seem to be a little better.

      --- demerphq
      my friends call me, usually because I'm late....

Re: comparing output to check if is an integer or float
by zerodata (Initiate) on Dec 08, 2002 at 03:03 UTC
    Many thanks everyone that has solved my problems.