Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Not a Number

by batt0usai (Initiate)
on Oct 18, 2002 at 07:09 UTC ( #206231=perlquestion: print w/ replies, xml ) Need Help??
batt0usai has asked for the wisdom of the Perl Monks concerning the following question:

I feel really stupid asking this qquestion... but I just cant find the syntax or the equivalent of NaN in perl. (not a number). Im trying to find out whether my variable is a number or not... help please?

Comment on Not a Number
Replies are listed 'Best First'.
Re: Not a Number
by rasta (Hermit) on Oct 18, 2002 at 07:24 UTC
Re: Not a Number
by robartes (Priest) on Oct 18, 2002 at 07:22 UTC
    You use regexes to check whether something is a valid number. The advantage of this is that you can easily adapt the regexes to whatever your interpretation of a number is. Here's an example out of the Cookbook:
    use strict; my $number="3.141529"; print "$number is a C float!\n" if $number=~/^([+-]?)(?=\d|\.\d)\d*(\. +\d*)?([Ee]([+-]?\d+))?$/;
    Chapter 2 of the Perl Cookbook provides numerous recipes for dealing with numbers in Perl. It comes highly recommended.


      NaN is an IEEE standard constant which stands for Not a Number. It is returned if an invalid operation exception occurs within an operation.

      For example, sqrt(-1) will return a number with a bit configuration that is recognized as NaN because this operation would result in an imaginary number.

      Therefore regexps don't help us in that issue.

      -- yuriy
        When I tried the sqrt(-1) example, I got the message
        Can't take sqrt of -1 at -e line 1.
        so it would seem that NaN is not used.
Re: Not a Number
by George_Sherston (Vicar) on Oct 18, 2002 at 10:48 UTC
    This question seems to come round with the fall of the leaf. When I asked it last year I didn't realise that it was so interesting and complex. Now I know, though I admit part of me just wants to say, like Sir Roger de Coverley would if he'd had a Babbage Engine, "well come on, I mean to say dash it all, a thing's either a number or it's not, don't you know?"

    George Sherston
      It may be a little late now but here's a funky little subroutine from merlyn that distinguishes between numbers and strings
      sub is_numeric { ($_[0] & ~ $_[0]) eq "0"; }
      The original post can be found here.


        OK, what will your subroutine return for '1e+2'?..
        perltod() works fine.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://206231]
Approved by tadman
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2015-12-01 05:46 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (794 votes), past polls