Scalar::Util::looks_like_number
I had a recent discussion with a Data::Dump::Color user about formatting ints/floats/stringy numbers differently. So here's a short summary of how core module function Scalar::Util's looks_like_number() can be used to detect the different data types:
perl -MScalar::Util=looks_like_number \
-E'printf "%6d # %s\n", $l=looks_like_number($_), $l<20?qq("$_"):$_
for ("str", 0, 1, "1", "1a", -1, "-1", 0.1, "0.1", -0.1, "-0.1", 1e20, nan, -nan, inf, -inf)'
0 # "str"
4352 # 0
4352 # 1
1 # "1"
0 # "1a"
4352 # -1
9 # "-1"
8704 # 0.1
5 # "0.1"
8704 # -0.1
13 # "-0.1"
8704 # 1e+20
36 # nan
44 # -nan
20 # inf
28 # -inf
Interestingly, on the stock Scalar::Util that comes with newer versions of Perl,
looks_like_number(undef) => 0
but on very old versions (such as that bundled with Perl 5.8.1)looks_like_number(undef) => 1
.BTW, it looks like maybe looks_like_number() will return canonical bool, so all this might be going away soon:
https://rt.cpan.org/Ticket/Display.html?id=94805
By then we'll need Scalar::Util (or some other module) to provide things like is_nan() (or looks_like_nan(), whatever), is_inf(), is_stringy_num(), is_stringy_int(), is_stringy_float(), etc.
But it's convenient to be able to differentiate different types of numbers in a single call though.
https://rt.cpan.org/Ticket/Display.html?id=94806
A new version of Scalar::Util has been released and now booleanizes looks_like_number(), so this trick can no longer be used. As an alternative, see chocolateboy's Scalar::Util::Numeric.
https://github.com/sharyanto/scripts/blob/master/list-numeric-scalar-types
Sample output (hopefully MT will behave here):