Check if a variable is a number - perl

Logic of code

if ( $var is a number ) {
Do something
}
else {
Do something else
}

My question is: How do I check if a variable is a number. All the reg ex that I came up with to match this is failing. Please help.

What pattern you need depends on what types of numbers you are expecting

  • float, rational, integers, etc.

The following pattern works for integers which may or may not have a leading
plus or minus sign.

if ($var =~ /^[+-]?\d+$/ ) {
    print "Is a number\n";
} else {
    print "Is not a number\n";
}

if you have Posix module

use POSIX;
@test = qw(zzz 456 vc32 xyz! 12.34);

foreach (@test) {
    print "$_ is digits\n" if isdigit $_;
    print "$_ is alpha\n" if isalpha $_;
} 

The POSIX example above only gives integers, not other real numbers...

Here's an alternative that I think may execute more quickly than using a regular expression or loading in an additional module and identifies decimal numbers... I'm sure there are probably faster ways, but this is the simplest that I can think of...

@list = qw(5 4.4 0 -1.2 asdf 12asdf asdf12 1.2e3 0e0);
foreach $thing (@list){
if (($thing * 1) eq $thing){
print "$thing is a number!\n";
}else{
print "$thing is NOT a number!\n";
}
}

Note that ("12asdf" * 1) equals 12...
Also note that the above example does NOT work for numbers in scientific notation.

The only way I can think of to make it work for numbers in sci-notation would be to use a regular expression. I don't like having to do that though because there is always room for exceptions when using regular expressions. Also, execution times could be much faster if there were a perlfunction "isreal" that returned the result; and since so many operations built into perl must have to know weather the scalar is real or not anyway, I don't see why it isn't already a function... For something as fundamental as this it really should be.
On another note, I saw a cpan module called Test::Data::Scalar where it looks like somebody has started developing some scalar test functions, but the description still claims that the "number_ok" function still needs work because it basically only tests for digits right now.

Anyway, if your program can accept things like the "12asdf" as 12, then the following will probably work for scientific numbers (except for 0 when it is written in scientific notation, ex: "0e0").

@list = qw(5 4.4 0 -1.2 asdf 1.2e3asdf asdf12 1.2e3 0e0);
foreach $thing (@list){
$number_part = ($thing * 1);
$float_number = sprintf ("%e",$thing);
#note: in this case $thing gets interpreted to be the same as $number_part
if (($number_part eq $thing) or (($value != 0) and ($number_part ne $float_number)){
print "$thing is a number!\n";
}else{
print "$thing is NOT a number!\n";
}
}

I'm still looking for more complete solutions though. If anyone has any better ideas, please post.