Perl Programming/Numbers

Previous: Strings Index Next: Comments


Numbers

edit

Numbers in Perl do not have to be enclosed in any kind of punctuation; they can be written as straight numbers.

Floating-point numbers

edit

Here are some acceptable floating point numbers:

0.1, -3.14, 2.71828…

Integers

edit

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

Non-decimal numbers

edit

I'll dwell on this topic for a little longer than the other types of numbers. In Perl you can specify not only 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

Number Operators

edit

Just like strings, numbers have operators. These operators are quite obvious so I'll just give a quick example of each one.

The +, - , /, and * operators

edit

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

Perl also has the familiar increment, decrement, plus-equals, and minus-equals operators from C:

$a++    # evaluate, then increment
++$a    # increment, then evaluate
$a--    # evaluate, then decrement
--$a    # decrement, then evaluate
$a += 5 # plus-equals operator, adds 5 to $a. Equivalent to $a = $a + 5
$a -= 2 # minus-equals operator, subtracts 2 from $a. Equivalent to $a = $a-2

Now let's look at one more operator that's a little less obvious.

The ** Operator

edit

The ** operator is simply the exponentiation 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)

Exercises

edit
  • 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.


Previous: Strings Index Next: Comments