develooper Front page | perl.beginners | Postings from May 2001

Re: test for real number

Thread Previous | Thread Next
From:
merlyn
Date:
May 31, 2001 07:10
Subject:
Re: test for real number
Message ID:
m1ae3tboeu.fsf@halfdome.holdit.com

The most comprehensive test for a real number is to let Perl
do it itself:

    sub is_number {
      my $bad = 0;
      local $SIG{__WARN__} = sub { $bad++ };
      local $^W = 1;
      my $guess = shift;
      $guess += 0;
      return not $bad;
    }

If adding 0 didn't trigger the numeric warning, then it's a good number!

For integers, you can narrow it down:

    sub is_integer {
      my $bad = 0;
      local $SIG{__WARN__} = sub { $bad++ };
      local $^W = 1;
      my $guess = shift;
      return $guess == int($guess) and not $bad;
    }

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About