Learning Perl

Learning PerlSearch this book
Previous: 2.1 What Is Scalar Data?Chapter 2
Scalar Data
Next: 2.3 Strings
 

2.2 Numbers

Although a scalar is either a number or a string,[1] it's useful to look at numbers and strings separately for the moment. Numbers first, strings in a minute... .

[1] Or a reference, but that's an advanced topic.

2.2.1 All Numbers Use the Same Format Internally

As you'll see in the next few paragraphs, you can specify both integers (whole numbers, like 17 or 342) and floating-point numbers (real numbers with decimal points, like 3.14, or 1.35 times 1025). But internally, Perl computes only with double-precision floating-point values.[2] This means that there are no integer values internal to Perl; an integer constant in the program is treated as the equivalent floating-point value.[3] You probably won't notice the conversion (or care much), but you should stop looking for integer operations (as opposed to floating-point operations), because there aren't any.

[2] A "double-precision floating-point value" is whatever the C compiler that compiled Perl used for a double declaration.

[3] Unless you use "integer mode," but that's not on by default.

2.2.2 Float Literals

A literal is the way a value is represented in the text of the Perl program. You could also call this a constant in your program, but we'll use the term literal. Literals are the way data is represented in the source code of your program as input to the Perl compiler. (Data that is read from or written to files is treated similarly, but not identically.)

Perl accepts the complete set of floating-point literals available to C programmers. Numbers with and without decimal points are allowed (including an optional plus or minus prefix), as well as tacking on a power-of-10 indicator (exponential notation) with E notation. For example:

1.25     # about 1 and a quarter
7.25e45  # 7.25 times 10 to the 45th power (a big number)
-6.5e24  # negative 6.5 times 10 to the 24th
         # (a "big" negative number)
-12e-24  # negative 12 times 10 to the -24th
         # (a very small negative number)
-1.2E-23 # another way to say that

2.2.3 Integer Literals

Integer literals are also straightforward, as in:

12
15
-2004
3485

Don't start the number with a 0, because Perl supports octal and hexadecimal (hex) literals. Octal numbers start with a leading 0, and hex numbers start with a leading 0x or 0X.[4] The hex digits A through F (in either case) represent the conventional digit values of 10 through 15. For example:

0377 # 377 octal, same as 255 decimal
-0xff # negative FF hex, same as -255 decimal

[4] The "leading zero" indicator works only for literals, not for automatic string-to-number conversion. You can convert a data string that looks like an octal or hex value into a number with oct or hex.


Previous: 2.1 What Is Scalar Data?Learning PerlNext: 2.3 Strings
2.1 What Is Scalar Data?Book Index2.3 Strings