Open In App

Perl | Automatic String to Number Conversion or Casting

Perl has a different way to deal with the operators because here operator defines how the operands will behave but in other programming languages, operands define how an operator behaves. Casting refers to the conversion of a particular variable’s data type to another data type. For example, if there is a string “1234” and after converting it to int data type the output will be an integer 1234. Conversion of string to integer in Perl has many ways. One is to use Typecasting, while the other one involves use of ‘sprintf‘ function. Sometimes people do not use the word casting in Perl because the whole thing of conversion is automatic.

Typecasting



Type conversion happens when we assign the value of one data type to another. If the data types are compatible, then Perl does Automatic Type Conversion. If not compatible, then they need to be converted explicitly which is known as Explicit Type conversion. There are two types of typecasting:

sprintf function

This sprintf function returns a scalar value, a formatted text string, which gets typecasted according to the code. The command sprintf is a formatter and doesn’t print anything at all.




# Perl code to demonstrate the use 
# of sprintf function
  
# string type
$string1 = "25";
  
# using sprintf to convert 
# the string to integer
$num1 = sprintf("%d", $string1);
  
$string2 = "13";
  
# using sprintf to convert 
# the string to integer
$num2 = sprintf("%d", $string2);
  
# applying arithmetic operators
# on int variables 
print "Numbers are $num1 and $num2\n";
  
$sum = $num1 + $num2;
print"Sum of the numbers = $sum\n";

Output:

Numbers are 25 and 13
Sum of the numbers = 38

Article Tags :