Ashutosh Arya Ashutosh Arya - 11 months ago 119
Perl Question

Behavior of Scalar::Util::looks_like_number in Perl

I am trying to find out if an input is number or string. I came across

and cannot understand the values it returns.

use warnings;
use Scalar::Util qw(looks_like_number);

my $name = 11;
print looks_like_number ($name);

This code prints
contains a string and a static number if
contains an integer (i.e. 4352 for each integer).

I am using Perl on Windows.

Answer Source

This is what the documentation says:

looks_like_number EXPR

Returns true if perl thinks EXPR is a number. See "looks_like_number" in perlapi.

The link to perlapi in this quote is not really helping us a lot unfortunately:

Test if the content of an SV looks like a number (or is a number). Inf and Infinity are treated as numbers (so will not issue a non-numeric warning), even if your atof() doesn't grok them. Get-magic is ignored.

I32   looks_like_number(SV *const sv)

In my case, your code will return an integer that is not 0, which is true.

  • I got 4352 when I used 11.
  • When I used '11' I got 1.

All of these are true, so that works.

  • When I put 'test' or 'foobar' I got 0, which is not true.
  • I never got a 1 for anything that did not look like a number.
  • I tried '1e1' and it printed 4, which is a true value, and the input looked like a number in scientific notation.

So, I'd say it always returns something true if Perl thinks the input looks like a number, though I do not know what exactly that true value represents. I cannot confirm that it also returns true with a name.