in reply to Is A Number

Hi,

I had a little play and noticed that your IsNumber() sub returns true for integers with embedded (and/or trailing) garbage, unless the garbage is alphabetic or whitespace.
Seemed odd ... but, of course, FAIK it's quite possible that the integer inputs you're receiving are either guaranteed to have no such garbage or are to be deemed acceptable if they include such garbage.
For the input array in the following script (where I also compare the IsNumber() and looks_like_number() results), IsNumber returns "1" for all but the final input.
use strict; use warnings; use Scalar::Util qw(looks_like_number); use Test::More; my @in = ('99/999998', '9999*9998', '9999-9998', '9999+9998', '9999:9998', '9999@:%?', '9999@:%?9998', '9999ABCD9998',); for(@in) { cmp_ok(IsNumber($_), '==', looks_like_number($_), "$_: " . IsNumber +($_)); } done_testing(); sub IsNumber { my ($string) = @_; my $valid = 0; my $count = $string =~ tr/\.//; if ( $string =~ m/[a-zA-Z\ \[\]]/ ) { $valid = 0; } elsif ( $string =~ /[^\x00-\x7F]/ ) { $valid = 0; } elsif ( $count > 1 ) { $valid = 0; } elsif ( $string =~ m/[#@':;><,.{}[]=!"£$%^&*()]/ ) { $valid = 0; } elsif ( $string =~ m/^[+-]?\d+$/ ) { $valid = 1; } elsif ( $string =~ m/^[+-]?[0-9]+[.]?[0-9]+/ ) { $valid = 1; } return $valid; }
Outputs:
not ok 1 - 99/999998: 1 # Failed test '99/999998: 1' # at try.pl line 13. # got: 1 # expected: not ok 2 - 9999*9998: 1 # Failed test '9999*9998: 1' # at try.pl line 13. # got: 1 # expected: not ok 3 - 9999-9998: 1 # Failed test '9999-9998: 1' # at try.pl line 13. # got: 1 # expected: not ok 4 - 9999+9998: 1 # Failed test '9999+9998: 1' # at try.pl line 13. # got: 1 # expected: not ok 5 - 9999:9998: 1 # Failed test '9999:9998: 1' # at try.pl line 13. # got: 1 # expected: not ok 6 - 9999@:%?: 1 # Failed test '9999@:%?: 1' # at try.pl line 13. # got: 1 # expected: not ok 7 - 9999@:%?9998: 1 # Failed test '9999@:%?9998: 1' # at try.pl line 13. # got: 1 # expected: ok 8 - 9999ABCD9998: 0 1..8 # Looks like you failed 7 tests of 8.
Cheers,
Rob

PS
I also did not expect that IsNumber('1.123e4') would return 0. But again, I don't know much about the possible inputs or the criteria for assessing them.