in reply to numeric comparison

This is the function I used to use for this.

sub is_numeric{ use POSIX (); !(POSIX::strtod($_[0]))[1]; }

However, if you download and build the latest cpan version of Scalar::Util (the version that comes with 5.8.0 doesn't have it), it provides access to perl's internal looks_like_number(); which ought to be quicker than either strtod() or a regex.

NOTE: If your not set up to build XS modules, then List::Util and Scalar::Util will silently fall back to using Perl implementations of the functions they provide. In the case of Looks_like_number(), this is a regex.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller

Replies are listed 'Best First'.
Re: Re: numeric comparison
by Zaxo (Archbishop) on Jul 15, 2003 at 14:44 UTC

    Perl 5.8.1's stock Scalar::Util has looks_like_number(). Here's a little workout to show what it can and can't do,

    use Scalar::Util 'looks_like_number'; my @candidates = qw/ 1 1.1 1,1 0E0 0e0 0377 100_000 0xdeadbeef/; print $_, looks_like_number($_)? ' is' : ' is not', ' a number.', $/ for @candidates; __END__ 1 is a number. 1.1 is a number. 1,1 is not a number. 0E0 is a number. 0e0 is a number. 0377 is a number. 100_000 is not a number. 0xdeadbeef not is a number.

    After Compline,
    Zaxo

      I was a bit surprised by 100_000 not being recognised as a number but then I tried this

      print 3 + '0xdeadbeef'; Argument "0xdeadbeef" isn't numeric in addition (+) at ... 3 print 3 + 0xdeadbeef; 3735928562 print 3+ '100_000'; Argument "100_000" isn't numeric in addition (+) at ... 103 print 3+ 100_000; 100003

      Which I guess means that the code used to extract a number from a string at runtime is a different routine to that used for parsing numeric constants at compile time. Which is slightly disappointing, but is probably done that way for very good reasons.

      I just wish that the version of Scalar-List-Utils on the AS 5.8 list included the compiled XS code. That is that possible isn't it?


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller