Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to determine if something is numeric?

by Ovid (Cardinal)
on Jan 30, 2004 at 19:19 UTC ( #325344=note: print w/replies, xml ) Need Help??


in reply to How to determine if something is numeric?

If I've understood your specs correctly:

use Scalar::Util 'looks_like_number'; if (0 != substr($var,0,1) and looks_like_number($var)) { # it's a number }

Update: As sporty pointed out below, this breaks on negative numbers. I didn't see that dash in your post. Here's the fix:

use Scalar::Util 'looks_like_number'; if ($var !~ /^-?0/ && looks_like_number($var)) { # it's a number }

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re: Re: How to determine if something is numeric?
by mifflin (Curate) on Jan 30, 2004 at 19:34 UTC
    we must have different versions of something.
    when I run that code id get the following error

    erickn@hestia:/home/erickn/wo> perl x "looks_like_number" is not exported by the Scalar::Util module Can't continue after import errors at x line 5 BEGIN failed--compilation aborted at x line 5.

    line 5 is the use line

    I'm using perl 5.8.0
    It looks like Scalar::Util uses List::Util and that version in my system is 1.07_00
    any ideas?
      mifflin,
      looks_like_number was introduced in version 1.10 of Scalar::Util. The sub looks like this:
      sub looks_like_number { local $_ = shift; # checks from perlfaq4 return 1 unless defined; return 1 if (/^[+-]?\d+$/); # is a +/- integer return 1 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/); # +a C float return 1 if ($] >= 5.008 and /^(Inf(inity)?|NaN)$/i) or ($] >= 5.006 +001 and /^Inf$/i); 0; }
      As I stated in my reply - I do not think this meets your requirements because it also handles decimals, scientific notation, NaN, and Inf.

      Cheers - L~R

      It looks like Scalar::Util uses List::Util and that version in my system is 1.07_00 any ideas?
      Upgrade :)

      MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
      I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
      ** The third rule of perl club is a statement of fact: pod is sexy.

Re: Re: How to determine if something is numeric?
by exussum0 (Vicar) on Jan 30, 2004 at 19:42 UTC
    This breaks on negative numbers.

    Play that funky music white boy..

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2021-04-16 10:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?