1. Perl
  2. Numerical value
  3. Automatic conversion of numbers and strings

Automatic conversion of numbers and strings

Perl implicitly automatically converts strings and numbers. It is very easy to write a script because there is no need to explicitly convert strings and numbers as in C and Java.

my $num1_str = "100";
my $num1 = 100;

my $num1_total = $num1_str + $num1;

When the string "100" is used as a numerical value, it is automatically converted to 100 and calculated.

Learn how Perl interprets strings as numbers.

my $num2_str = "34A11";

"34A11" is converted to 34 when used as a number. The part of the number that continues from the beginning is converted to a number.

If you write use warnings ;, you will be warned if you try to use a string that does not consist only of numbers as a number.

The empty string "" is calculated as 0 (again, it is not a number, so a warning is given).


This is an example to check the automatic conversion of numbers and strings.

use strict;
use warnings;

my $num1_str = "100";
my $num1 = 100;

my $num1_total = $num1_str + $num1;

print "(1) Automatic conversion from string to number\n";
print "\$num1_total = $num1_total\n\n";

# If this string is used as a number, then 34
# Treated as .
# As a number if use warnings are enabled
# If you try to use it, you will be warned.
my $num2_str = "34A11";

my $num2 = 3;

my $num2_total = $num2_str + $num2;

print "(2) Calculated using the numbers that continue from the beginning.\n";
print "\$num2_total = $num2_total\n";

Related Informatrion