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
| [reply] [d/l] [select] |
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
| [reply] [d/l] |
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....
| [reply] [d/l] |
Many thanks everyone that has solved my problems.
| [reply] |