Perl Programming/Numbers
From Wikibooks, the open-content textbooks collection
Contents |
[edit] Numbers
Numbers in Perl do not have to be enclosed in any kind of punctuation; they can be written as straight numbers.
[edit] Floating Point Numbers
Here are some acceptable floating point numbers:
0.1, -3.14, 2.71828...
[edit] Integers
Integers are all whole numbers and their negatives (and 0): {... -3, -2, -1, 0, 1, 2, 3 ...}.
Here are a few examples of integers:
12, -50, 20, 185, -6654, 6654
The following examples are not integers:
15.5, -3.458, 3/2, 0.5
[edit] Non-decimal Numbers
I'll dwell on this topic for a little longer than the other types of numbers. In Perl you can not only specify decimal numbers, but also numbers in hex, octal, and binary. If you are not familiar with how these systems work, you can try these Wikipedia articles:
In Perl you have to specify when you are going to write a non-decimal number. Binary numbers start with an 0b, so here are some possible binary numbers:
0b101011101 0b10
Octal numbers start with 0 ("zero"), so here are some possible octal numbers:
015462 062657 012
Hexadecimal numbers start with 0x, so here are some possible hexadecimal numbers:
0xF17A 0xFFFF
[edit] Number Operators
Just like strings, numbers have operators. These operators are quite obvious so I'll just give a quick example of each one.
[edit] The +, - , /, and * Operators
These operators are pretty obvious, but here are some examples:
100 + 1 # That's 101 100 - 1 # That's 99 100 / 2 # That's 50 100 * 2 # That's 200
Now let's look at one more operator that's a little less obvious.
[edit] The ** Operator
The ** operator is simply the exponentation operator. Here's another example:
2**4 # That's 16, same as 24 4**3**2 # that's 4**(3**2), or 49, or 262144
| Extra! The modulus operator (%) can be used to find the remainder when dividing two numbers. If that doesn't make sense now, that's fine, it's not that important. (Note, this returns 0 when used on floating point numbers) |
[edit] Exercises
- Remember the x operator? Use a mathematical expression as the number of times to repeat the string, see what happens.
- Write a program like our original hello world program except make it print a mathematical expression.

