Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if a variable has a numeric value in Perl?

Tags:

numbers

perl

Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:

if (is_number($x)) { ... } 

would be ideal. A technique that won't throw warnings when the -w switch is being used is certainly preferred.

like image 202
Derek Park Avatar asked Aug 15 '08 19:08

Derek Park


People also ask

How do you check if a variable contains a number?

In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.

How do I check if a string contains only numbers in Perl?

let b = s. chars(). all(char::is_numeric);

What does numeric value look like?

A numeric value contains only numbers, a sign (leading or trailing), and a single decimal point.


1 Answers

Use Scalar::Util::looks_like_number() which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this. Note that the strings "inf" and "infinity" are treated as numbers.

Example:

#!/usr/bin/perl  use warnings; use strict;  use Scalar::Util qw(looks_like_number);  my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);  foreach my $expr (@exprs) {     print "$expr is", looks_like_number($expr) ? '' : ' not', " a number\n"; } 

Gives this output:

1 is a number 5.25 is a number 0.001 is a number 1.3e8 is a number foo is not a number bar is not a number 1dd is not a number inf is a number infinity is a number 

See also:

  • perldoc Scalar::Util
  • perldoc perlapi for looks_like_number
like image 66
nohat Avatar answered Sep 23 '22 20:09

nohat