Previous Page Next Page

6.2. Mixing Data Types

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"

Table 6.1. How Strings Are Converted to Numbers
Stringrightwards double arrow Converts to rightwards double arrowNumber
"123 go!" 123
"hi therev 0
"4e3" 4000
"-6**3xyz" -6
" .456!!" 0.456
"x.1234" 0
"0xf" 0


Example 6.1.

(The Script)
1   $x = "     12hello!!" + "4abc\n";
# Perl will remove leading whitespace and trailing non-numeric
# characters
2   print "$x";
3   print "\n";

4   $y = ZAP . 5.5;
5   print "$y\n";

(Output)
2   16
5   ZAP5.5

Explanation

  1. The plus sign (+) is a numeric operator. The strings " 12hello!!" and "4abc\n" are converted to numbers (leading whitespace and trailing non-numeric characters are removed) and addition is performed. The result is stored in the scalar $x.

  2. The scalar $x is printed.

  3. Since the \n was stripped from the string 4\n in order to convert it to a number, another \n is needed to get the newline in the printout.

  4. The period (.), when surrounded by whitespace, is a string operator. It concatenates two strings. The number 5.5 is converted to a string and concatenated to the string ZAP.

  5. The value of the scalar $y is printed.

Previous Page Next Page