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

4 Comments

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.

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays). My CPAN ID: SHARYANTO. I'm sedusedan on perlmonks. My twitter is stevenharyanto (but I don't tweet much). Follow me on github: sharyanto.