I need a routine that distinguishes between a number (in decimal representation) and a string that's not a legal number (let's say it returns 1 for a number, 0 otherwise).
As perl treats any string, that starts with a legal number, as a number, the simple solution
$numorstr*1?1:0
doesn't work (and of course doesn't give the correct answer for the number 0).
Assuming the checked value is not a reference, below is what I've come up with this problem: can anyone see a simpler (or more robust) solution?
NOTE: perl allows underscores in number representation as thousands separators, but from some tests I assumed that this is only allowed when the number is input as such (e.g. $a=1_000 without string delimiters) and that perl strips away those underscores in compiling that type of representation. Hence underscores are not specially treated in the routine.
prex1
: Online tools for structural design
: Magnetic brakes for fun rides
: Air bearing pads
As perl treats any string, that starts with a legal number, as a number, the simple solution
$numorstr*1?1:0
doesn't work (and of course doesn't give the correct answer for the number 0).
Assuming the checked value is not a reference, below is what I've come up with this problem: can anyone see a simpler (or more robust) solution?
Code:
sub isnumber{
#returns 1 if passed value is a valid number in decimal representation
#0 otherwise
local($_);
for($_[0]){
s/^\s+//;
#leading spaces considered as non influent
return 0 unless length;
#a white or null string or an undef is considered a string
s/0+/0/g;
#multiple 0's treated as one (a string of many 0's is a 0)
return 1 if$_ eq'0';
#a single 0 is a number
s/^[\+\-]{1}//;
#only single leading +/- allowed
s/\.{1}//;
#only a single occurrence of decimal point allowed
s/^[0-9]+//g;
#strip away leading figures
if(s/^e//i){
#strip exponential symbol (now leading, if any)
return 0 unless length;
#no exponent:illegal for a number
s/^[\+\-]{1}//;
#only single leading +/- allowed in the exponent
s/^[0-9]+//g;
#strip away figures of the exponent
}
return length()?0:1;
#if length==0 was a number
}
}
prex1
: Online tools for structural design
: Magnetic brakes for fun rides
: Air bearing pads