Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Checking whether a $var is a number

by John M. Dlugosz (Monsignor)
on Sep 05, 2001 at 01:26 UTC ( [id://110163]=note: print w/replies, xml ) Need Help??


in reply to Checking whether a $var is a number

If you use a value as a number, it is a number.

A string that can't be parsed as a number at all will be zero. So, how about something like this:

if ($x==0 && substr($x,0,1) ne '0') { # deal with non-number } else { # deal with number }
In a real application, you will have a more precise definition of what you want. For example, a spreadsheet formula might be a literal number or a cell reference. For such things, you can write rules to match what your application needs and is documented to accept.

—John

Update:fixed typo in substr, reported by dga. Yea, I typed it without checking perlfunc, and I rarely use substr in real code.

Replies are listed 'Best First'.
Re: Re: Checking whether a $var is a number
by George_Sherston (Vicar) on Sep 05, 2001 at 01:37 UTC
    Yes. That (together with a || $x==1 && substr($x,1,1) ne '1') does exactly what I find myself wanting nine times out of ten. That is, what isNaN does in js. I'd find it useful to have a built in function, and maybe we're going to get one.

    § George Sherston
      Hmm, when does a scalar convert to 1 when it's not a number?

      Note that I didn't mention that you should already know that the value is "a string" rather than a reference or funky blessed overloaded object, but carefully worded it because I had that in mind.

Re: Re: Checking whether a $var is a number
by dga (Hermit) on Sep 05, 2001 at 22:59 UTC

    I think you have a typo in your substr which should be

    substr($x,0,1);

    Otherwise the case $x=0; falls into the not a number part of the if.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://110163]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-19 15:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found