How to check if a variable has a numeric value in Perl?


Suppose we get a variable at runtime in Perl and we want to check if the value that it contains is numeric or not, then we can use the two approaches shown in this tutorial. We will use two simple examples to demonstrate how it works.

Example 

The most basic approach is to use the length and do keywords and then ignore the warnings. Consider the code shown below for the same.

$x = 100;

if (length(do { no warnings "numeric"; $x & "" })){
   print "x is numeric\n";
} else {
   print "x is non-numeric\n";
}

Output

If you run the above code in a Perl compiler, you will get the following output on the terminal −

x is numeric

Example 

As soon as you change the variable "x" to something that is non-numeric, you will get the output of the "else" block in the "if" condition.

$x = 'abc';

if (length(do { no warnings "numeric"; $x & "" })){
   print "x is numeric\n";
} else {
   print "x is non-numeric\n";
}

Output

It will produce the following output

x is non-numeric

Example

Another approach to check whether a variable is numeric or not is to use the "Scalar::Util::looks_like_number()" API. It uses the internal "looks_like_number()" function of the Perl C API, which is the most efficient method. There is no difference between the strings "inf" and "infinity".

Consider the code shown below −

use warnings;
use strict;

use Scalar::Util qw(looks_like_number);

my @randomStuff =
  qw(10 15 .25 0.005 1.4e8 delhi India tutorialsPoint inf infinity);

foreach my $randomStuff (@randomStuff) {
   print "$randomStuff is", looks_like_number($randomStuff)? ' ': ' not', " a number\n";
}

Output

If you run this code in a Perl compiler, it will produce the following output on the terminal −

10 is  a number
15 is  a number
.25 is  a number0.005 is  a number
1.4e8 is  a number
delhi is not a number
India is not a number
tutorialsPoint is not a number
inf is  a number
infinity is  a number

Updated on: 26-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements