Link to home
Start Free TrialLog in
Avatar of woaini
woaini

asked on

numeric or string ??

Hi,

I would like to know if they have a way to analyse a value receive from a FORM, if it's a numeric number or a string ?

Thank.
Avatar of ozo
ozo
Flag of United States of America image

What do you consider a numeric number?
Have you tried the answers in perlfaq4 for "How do I determine whether a scalar is a number/whole/integer/float?"
Avatar of woaini
woaini

ASKER

Hi,

I mean by numeric = number . No, I haven't tried the answer in perlfaq4. Can you tell me where the location is ?

Thank.
Is "009" a number? "10e"? "10e-999"? "0xFF"? "1/2"? "Q.10057609"? "-inf"? "two"?  "four score and seven"?

perldoc perlfaq4
in the "Data: Misc" section.



Avatar of woaini

ASKER

0.10 ; 0.50 ; 1 ; 123 are number.
And "yes" or "no" are string.


Form values are passed as a string, if you want to use them as a number and you are not sure that it can be converted to a number, you should convert it to a number and catch an eventual error.

ASKER CERTIFIED SOLUTION
Avatar of ahoffmann
ahoffmann
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
print /[^\d.]/?"string":"number"; # might suffice for your examples
but it may or may not do what you want for "  .5\n", "+12300.e-2", "01", "", "1e9999", etc.
If you're not sure what you want to do in those cases, or if you're not sure which of the FAQ examples is most suitable for your purposes, perhaps you can tell us what you're trying to do with your values?
> beside ozo's comments, would folloing do what you expect?

>     $_=$string_to_check_if_numeric;
>     print "$_\n" if m/^[0-9]+\.?$|^[0-9]*\.?[0-9]+$/;

Probably not, at least in the general case.  Remember that a number may have an ignored underbar (i.e. 9_000 is legit... an Ada-ism).  Also, 4.7e12 is a legitimate number, which would fail your test.

ozo's comments about see the faq are relevant.  Tom covers this question exhaustively (btw, the final answer he gives is really 'you probably don't need to...')

b2pi, I know that my answer didn't cover *all* possibilities of writing "numbers", I just want it to be sufficent for woaini.
You even may think about pi, e (==euler), 2/3, and some more which are also legal "numbers" in some contexts.

If you would like to see a more perfect regex, have a look at the "Regualr Expressions" book and you'll see that even in perl it doesn't fit in a single line :-)

BTW, ozo's \d is more perlish than [0-9] (which I like for readability).
Avatar of woaini

ASKER

Thank a lot !