Checking
if a Perl Value is a Number
Because
Perl
stores both numbers and strings in the same variable, it's often
necessary to identify if a given variable contains a valid number. The
following simple subroutine returns true if the value passed to it is
numeric...
sub IsNumber
{
my $String = $_[0];
return $String =~ m/^-?([0-9]+\.)?[0-9]+$/;
}
It
makes use of Perl's regular expression processing. There is a speed
overhead in calling the regular expression parser but sometimes that's
a cost worth bearing, as here, when the simplicity of the code
outweighs the price in speed of execution.
This may
be used directly in a test as...
if
(IsNumber $MysteryVariable) {# do something... }
Find out more
by searching Google here...
|