Perl How to: Find a Given Variable String is numeric or not
This tutorial explains How to check given string is a number or not in Perl with Code examples
Scalar::Util
module provides theqw(looks_like_number)
function that checks given variable is a number or not. For example,looks_like_number("111")
returns a boolean value, use in the conditional if statement to check as a number or not.- Second, append a variable with zero, and use the result in a conditional if statement.
- Third, use the [Regexp::Common] module that uses a regular expression for real and integer numbers.
You can check my previous post, on How to Convert String to Number in Perl.
Dart How to check whether a String is Numeric or not
This approach uses the parse method of double for floating and number for without decimals
The Scalar::Util
module has a function looks_like_number
internally uses converts string literal into a number and checks result is a number or not.
looks_like_number
Here is an example isNumeric Extension method on the String class
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
my $var1="123";
print "$var1 contains", looks_like_number($var1) ? '' : ' not', " a number\n";
print "a",looks_like_number($var1),"test";
my $var2="abc";
print "$var2 contains", looks_like_number($var2) ? '' : ' not', " a number\n";
my $var3="1a23";
print "$var3 contains", looks_like_number($var3) ? '' : ' not', " a number\n";
my $var4="__";
print "$var4 contains", looks_like_number($var4) ? '' : ' not', " a number\n";
Output:
123 contains a number
a1testabc contains not a number
1a23 contains not a number
__ contains not a number
Second Approach; using regular expression
Regexp::Common🔗 module functions to process and test regular expressions with values in Perl. First, Install this module into your environment using the below code.
cpan Regexp::Common
Next, use this in your code.
It checks for real and floating numbers using regular expressions.
$RE{num}{real}
is a pattern that checks for real numbers.
Also, use $RE{num}{int}
, for Checking integer.
Here is an example
use warnings;
use strict;
use Regexp::Common;
is_number("111");
is_number("abc");
is_number("123.11");
# Sub routine for Checking a Number
sub is_number {
if ($_[0] =~ /$RE{num}{real}/) {
print "$_[0] is a number\n";
}
else{
print "$_[0] is not a number\n";
}
}
The third approach, append a variable with zero using the + operator, Check result is equal to a numeric value. You have to compare with a given value, So It is not recommended to use this approach Here is an example.
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
my $var1="123";
if ( $var1 + 0 eq 123) {
print "$var1 is a number\n";
}
else{
print "$var1 is not a number\n";
}