There are many approaches (also asserted by the acronym/phrase "TIMTOWTDI"). Just for fun, here's one of those:
#!/usr/bin/perl
use strict;
use warnings;
use 5.014;
# juliosergio's test.pl
print "Enter a number or string: ";
my $s = <STDIN>;
chomp $s;
if ( $s =~ /^[0-9,.E]+$/ ) { # char class, 1 or more of any of th
+ose specified
say "$s is a number\n"; # & the ^...$ restricts what's teste
+d.
} else {
say "'$s' may be a string\n"; # Not "isn't a number"
}
Execution:
C:\>numVSstring.pl
Enter a number or string: 123.2
123.2 is a number
C:\>numVSstring.pl
Enter a number or string: 1E3
1E3 is a number
C:\>numVSstring.pl
Enter a number or string: 17
17 is a number
C:\>numVSstring.pl
Enter a number or string: now is the time
'now is the time' may be a string
C:\>numVSstring.pl
Enter a number or string: III
'III' may be a string
This is not without "gotcha's." *1 The regular expression allows for the decimal digits 0 through 9, for the comma and dot which may be present is oft-encountered numbers, and an E to allow for scientific notation. But one could add and add and not cover all the possibilities withoiut making the regex unable to distinguish between numbers and words like "FIE".
Another tack one might take involves attempting to use an arithmetic operator on the input string. Perl will try to treat any string as a number as a bit of its DWIMery (and as a language in which variables are not crammed into particular 'types') but a failure to ID an input as a number won't necessarily be more conclusive than this is.
But, for further self-improvement or just for fun, you may want to to read perlop re 'Unary "-", or use Super Search or Google for "NaN" and "looks_like_number".
Bottom line: toolic's advice is probably about as good as any you'll find.
Update: Markup and substituted "digits" for numbers" in the para after the output.
Update 2 *1 For a knowledgeable discussion of some more of the "gotcha's," see the estimable jwkrahn's reply, below... and ++ that, too. |