Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalar::Util looks_like_number returning number types

I notice that looks_like_number doesn't simply return true/false as I'd assumed, but actually returns a byte indicating the type of number the perl internals say is stored in the scalar. For example:

perl  -e'use Scalar::Util qw/looks_like_number/; for (qw/ 1 3 10 34.23 545435.234 2343.0 234 -1423 1sddf -865178652134876152348761253487613254 sdf 24363456345636534563567253765734655  8764325hjkh435 iuh340874 &*^*& 786521948761324876132497821347816.23452345 -8762135487126387432.12435154243 0 nan inf/) { print $_, ": ", looks_like_number($_), "\n" } '
1: 1
3: 1
10: 1
34.23: 5
545435.234: 5
2343.0: 5
234: 1
-1423: 9
1sddf: 0
-865178652134876152348761253487613254: 10
sdf: 0
24363456345636534563567253765734655: 2
8764325hjkh435: 0
iuh340874: 0
&*^*&: 0
786521948761324876132497821347816.23452345: 6
-8762135487126387432.12435154243: 14
0: 1
nan: 36
inf: 20

It's not actually documented in Scalar::Util that I can find, just a mention of it returning perlapi's looks_like_number value, which also isn't in the documentation. At a glance, it appears to be:

  • & 1 = numeric
  • & 2 = 64 bit
  • & 4 = floating point
  • & 8 = negative
  • & 16 = infinity
  • & 32 = not a number

Are these masks portable and safe to use in code?

like image 236
Oesor Avatar asked Feb 14 '13 15:02

Oesor


2 Answers

No, if they are not documented, they are subject to change. And "numeric" and "64 bit" aren't really adequate descriptions of those flags. What they do do doesn't seem particularly useful to know in Perl code.

What problem are you trying to solve?

like image 132
ysth Avatar answered Sep 23 '22 00:09

ysth


Don't rely on undocumented behaviour, the return value is bound to Perl's internals, it can (and likely will) change in the future; it may even be different depending on which platform/architecture your script is running on!

If you want to test for NaN, infinity or negative zero, see this question.

like image 25
rjh Avatar answered Sep 22 '22 00:09

rjh