Different ways to convert String to number in Perl with code examples

This tutorial explains multiple ways to convert a String to a Number in Perl with Code examples.

  • Use String variable by append with a number o using the + operator.For example, "123"+0 returns number 123.
  • use the Int type constructor. For example, int("111") returns 111
  • sprintf function, Assign the result sprintf("%d", "98"); and variable holds number 98

How to Convert String to Number in Perl?

  • using string append with + Symbol The string contains a group of characters and letters, enclosed in double or single quotes in Perl. A number contains a numeric value.

For example, if the string contains numbers, Append with zero to return the number.

my $str = "123";
print $str + 0,"\n";

Output:

123

If the string contains mixed letters and numbers, letters are after numbers, It returns a number. Perl always processes the statements from left to right and Since It is a context-based programming language, it understands addition context as implicit and string is converted to zero, 999asd returns 999+0, appending explicit again with the + operator with 0 being the same number.

my $str = "999asd";
print $str + 0,"\n";

Output:

999

if the string contains letters before numbers, It treats it as a string, Converting string to a number is zero.

my $str = "asd999";
print $str + 0,"\n";

Output:

0

Please note with this approach, if the number starts with INF and nan, it always returns the same string as given below

my $str = "inf199";
print $str + 0,"\n";
my $str = "nan199";
print $str + 0,"\n";

Output:

inf
NaN

if the string contains letters in between numbers, it always returns the first number.


my $str = "1a99";
print $str + 0,"\n";

Output:

1
  • using int type constructor The second way, Using the int constructor, passes the string parameter to Int, and It casts to a number.

Here is a cast string to number using an int example

my $str = "456";
$number = int($str);
print $number,"\n"; # 456

my $str1 = "456abc";
$number1 = int($str1);
print $number1,"\n";# 456

my $str2 = "abc";
$number2 = int($str2);
print $number2;# 0

Output

456
456
0
  • use sprintf function

sprintf is a built-in function in Perl. It contains the first argument as a formatter and the second is a variable value. It converts a second value into a given format(first argument).

Here is a sprintf function in Perl to convert a string to a number.

my $str1 = "456";
$number1 = sprintf("%d", $str1);

print $number1,"\n"; # 456

my $str2 = "456abc";
$number2 = sprintf("%d", $str2);

print $number2,"\n"; # 456

my $str3 = "abc";
$number3 = sprintf("%d", $str3);
print $number3,"\n"; # 0

Conclusion

Since Perl does not do the automatic conversion from String to Number, So you have to manually do the conversion using different methods.