Automatic Conversion Between Numbers and Strings

For the most part, Perl automatically converts between numbers to strings as needed.  How does it know whether a number or a string is needed?  It all depends upon the operator being used on the scalar value.  If an operator expects a number (like + does), Perl will see the value as a number.  If an operator expects a string (like . does), Perl will see the value as a string.  So you don't need to worry about the difference between numbers and strings; just use the proper operators, and Perl will make it all work.

When a string value is used where an operator needs a number (say, for mulitplication), Perl automatically converts the string to its equivalent numeric value, as if it had been entered as a decimal floating-point value.[1]  So "12" * "3" gives the value 36.  Trailing non-number stuff and leading whitespace are discarded, so "12fred34" * " 3" will also give 36 without any complaints. [2]  At the extreme end of this, something that isn't a number at all converts to zero.  This would happen if you used the string "fred" as a number.

Likewise, if a numeric value is given when a string value is needed (say, for string concatenation), the numeric value is expanded into whatever string would have been printed for that number.  For example, if you want to concatenate the string Z followed by the result of 5 multiplied by 7[3], you can say this simply as:

"Z" . 5 * 7 # same as "Z" . 35, or "Z35"

In other words, you don't really have to worry about whether you have a number or a string (most of the time).  Perl performs all the conversions for you.[4]   And if you're worried about efficiency, don't be.  Perl generally remembers the result of a conversion so that it's done only once.

Next:  Scalar Variables

OR

Main Menu for this topic





























[1] The trick of using a leading zero to mean a nondecimal value works for literals, but never for automatic conversion.  Use hex() or oct() to convert those kinds of strings.

Return to the page from whence you came






























[2] Unless you request warnings, which we'll discuss in a moment.

Return to the page from whence you came






























[3] We'll see about precedence and parentheses shortly.

Return to the page from whence you came






























[4] It's usually not an issue, but these conversions can cause small round-off errors.  That is, if you start with a number, convert it to a string, then convert that string back to a number, the result may not be the same number as you started with.  It's not just Perl that does this; it's a consequence of the conversion process, so it happens to any powerful programming language.

Return to the page from whence you came