Q&A

Q1: How do I define a variable so that it'll only contain a number?
A1: You can't. Perl doesn't have strong number types the way other languages do; the closest you can get is a scalar variable, and that can contain either a number or a string.

Most of the time, this will not matter; Perl will convert strings to numbers for you and vice versa.

Q2:But what if I end up with data in string form that isn't a number and I try to do something numeric with it?
A2: The default behavior is as I described in the section on “Converting Between Numbers and Strings.” Strings with no numeric content will become 0. Strings that start with numbers and then revert to characters will lose the characters.

If you have warnings turned on in your Perl script, then Perl will warn you when you're trying to do things to nonnumeric data so you can correct the operation of your scripts before you have this problem.

If you're worried about getting nonnumeric data from the user, you should be checking their input when they make it. We did some of this today; I'll show you more tricks for verifying input on Day 6 and Day 9.

Q3:My calculations are returning floating-point numbers with way too many numbers after the decimal point. How do I round off numbers so they only have two decimal places?
A3: See the section on “Arithmetic Operators,” where I explain how to use printf and sprintf to do this very thing.
Q4:But printf and sprintf are string functions. I want to round off numbers.
A4: Both numbers and strings are forms of scalar data in Perl. What you can do to one, you can do to the other (in many cases). Use printf and sprintf. Really.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset