If you have operands of mixed types (i.e., numbers and strings), Perl will make the appropriate conversion by testing whether the operator expects a number or a string for an operand. This is called overloading the operator.
If the operator is a numeric operator, such as an arithmetic operator, and the operand(s) is a string, Perl will convert the string to a decimal floating point value. Undefined values will become zero. If there is leading whitespace or trailing non-numeric characters, they will be ignored, and if a string cannot be converted to a number, it will be converted to zero.
$string1 = "5 dogs "; $string2 = 4; $number = $string1 + $string2; # Numeric context print "Number is $number.\n"; # Result is 9
Likewise, if Perl encounters a string operator and the operand(s) is numeric, Perl will treat the number as a string. The concatenation operator, for example, expects to join two strings together.
$number1 = 55; $number2 = "22"; $string = $number1 . $number2; # Context is string print "String is string.\n" # Result is "5522"
String | Number | |
---|---|---|
"123 go!" | 123 | |
"hi therev | 0 | |
"4e3" | 4000 | |
"-6**3xyz" | -6 | |
" .456!!" | 0.456 | |
"x.1234" | 0 | |
"0xf" | 0 |