in reply to Portable way of checking if a scalar is a number / integer / float

Can't locate loadable object for module Scalar::Util::Numeric

Scalar::Util::Numeric is an XS module, which means it must always be compiled against whatever version of Perl is on the user's machine. So your requirement

I don't want to require users to install anything - just git clone and it should work.

is the first thing I would question. Yes, even you can use CPAN, and so can your users.

Yes, there is Scalar::Util::Numeric::PP and you could use this for your Option 1. But then the problem becomes maintenance: You'd have to always make sure to update your module if there are changes or fixes to the upstream module - I guess one could call this a variation of DRY. Similar issue with your Option 2: Sure, you can reinvent the wheel, but then remember to write enough tests to cover all edge and corner cases etc.

Though this is just a variation of the above, another option might be to take the regexes produced by Regexp::Common::number and integrate those into your code. This has the same problem as above, but at least it's a bit less code to copy over...

See also the FAQ How do I determine whether a scalar is a number/whole/integer/float?

By the way, in regards to the title of the question, there is an important distinction sometimes missed by people that the question should be "does this string look like a integer/float", and not "does this Perl scalar hold a number or a string", because oftentimes Perl scalars can be both a number and a string depending on what context they're used in, and therfore, in Perl, this is not the right question to ask. (The only exception might be when writing a data serialization tool, and even those often run into trouble in making that distinction.)

  • Comment on Re: Portable way of checking if a scalar is a number / integer / float
  • Download Code

Replies are listed 'Best First'.
Re^2: Portable way of checking if a scalar is a number / integer / float
by bishop729 (Initiate) on May 13, 2023 at 22:57 UTC

    Thank you for pointing me to Scalar::Util::Numeric::PP. I installed it using CPAN and copied over the source into my repo and it works.

    use lib dirname(__FILE__); do "Scalar/Util/Numeric/PP.pm" or die;

    To your point that:

    Yes, even you can use CPAN, and so can your users.

    For now my quick-and-dirty solution is sufficient. If I find myself adding more dependencies I'll create an install script that installs cpan and the necessary libraries.

    Thanks for the tip about scalars. It had slipped my mind that strings and numbers have distinct internal representation in Perl

    Edit: solution was incorrect; I fixed it.