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?

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.