The conversion of type in Perl is quite simple: just combined the source type with the target type. For instance, if the source type is of number type and we want to convert it into a string, simply concatenate it with an empty string, then it will turn into a string, such as follows:
my $number = 5.5; # This is of number type
my $strNumber = $number .= ''; # Become '5.5'
Note: Operator .=
indicates a string concatenation.
In reverse, if we want to convert a string into of number type, we can simply add a 0 to it. It is shown below:
my $str = "5.5"; # This is of string type
my $numberFromStr = $str + 0; # Become 5.5 instead of '5.5'
Note: The number is base 10. If there is a need to convert the string into other base form, use the functions oct()
or hex()
.
This could be especially useful when trying to test a value’s booleaness# if it is of different type.