Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of Scalar::Util::looks_like_number in Perl

Tags:

perl

I am trying to find out if an input is number or string. I came across looks_like_number 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 1 if $name contains a string and a static number if $name contains an integer (i.e. 4352 for each integer).

I am using Perl on Windows.

like image 249
Ashutosh Arya Avatar asked Oct 05 '13 18:10

Ashutosh Arya


1 Answers

You forgot to ask a question! Here are two possibilities.

Why doesn't it always return the same value for true?

Why not? It returns a true value as documented. It makes no difference which true value it is.

What is the value returned?

If the scalar contains a string, it uses grok_number which has specific document return values.

The type of the number is returned (0 if unrecognised), otherwise it is a bit-ORed combination of IS_NUMBER_IN_UV, IS_NUMBER_GREATER_THAN_UV_MAX, IS_NUMBER_NOT_INT, IS_NUMBER_NEG, IS_NUMBER_INFINITY, IS_NUMBER_NAN (defined in perl.h).

Otherwise, it uses

SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK)

You can't tell which of the two was used, so you can't ascribe meaning to the value, which is why it's undocumented.

like image 148
ikegami Avatar answered Oct 11 '22 12:10

ikegami