Monday, March 16, 2009

Perl Handles Numbers

Perl can handle both whole numbers (integers, like 37) and floating-point numbers (real numbers with decimal points, like 17.5 or -235.2). Internally, Perl handles both as 'double precision floating-point values', but in Perl code they are treated the same way and can be used interchangeably. Here are some examples of number literals :

128 (positive integer)
-127 (negative integer)
0
17.5 (positive floating number)
-4.6E13 (negative 4.6 times 10 to the 13th power. E denotes exponential notation)

The last numeric literal above is an example of exponential or scientific notation, used when you need to work with very large or very small numbers.

In addition to decimal literals, Perl supports octal (base 8) and hexadecimal (base 16) literals.

Octal literals are denoted by a leading 0, and hex literals by a leading 0x or 0X.

For example:
0177 # 177 octal, same as 127 decimal
0xf0 # f0 hexadecimal, same as 240 decimal
- 0Xff # negative ff hexadecimal, same as -255 in decimal

Many people writing Perl programs will never need to work with octal or hex numbers - but be careful not to specify decimal numbers with a leading zero, because Perl will interpret them as octal.

No comments: