1. Perl
  2. Numerical value
  3. here

Determine if the string represents an integer

To determine if string represents an integer, regular expression > Is used. Determines if a regular expression is made up of numbers from start to finish.

/^[0-9]+$/

To determine if it's an integer, just add to the regular expression above that it doesn't matter if it's prefixed with + or-.

/^[+-]? [0-9]+$/

Example

This is an example to judge whether a variable is a numerical value.

use strict;
use warnings;

print "1: Determine if the string represents the correct number\n";

my $num1 = "345";
# Determining if the string is only numbers
# Read "One or more numbers continue from the beginning to the end"
if ($num1 =~ /^[0-9]+$/) {
  print "$num1 is a string of numbers only.\n";
}

# Judgment whether it is an integer
my $num2 = "-123";

# "With or without + or-at the beginning, after that
# One or more numbers follow to the end "
if ($num2 =~ /^[+-]? [0-9]+$/) {
  print "$num2 is an integer.\n";
}

Related Informatrion