3. Expressions

Perl supports such mathematical operators as +, -, * (multiplication), and parenthesis (( ... )). An example is worth a thousand words:

print "5 + 6 = ", 5+6, "\n";
print "(2 + 3) * 6 = ", (2+3)*6, "\n";
print "2 + 3 * 6 = ", 2+3*6, "\n";
print "2 raised to the power of 8 is ", 2**8, "\n";
print "10-5 = ", 10-5, ". 5-10 = ", 5-10, "\n";
print "2/3 = ", 2/3, "\n";

The output of this program is:

5 + 6 = 11
(2 + 3) * 6 = 30
2 + 3 * 6 = 20
2 raised to the power of 8 is 256
10-5 = 5. 5-10 = -5
2/3 = 0.666666666666667

The operators have the same precedence as their mathematical equivalents. The parenthesis are useful for making sure a sub-expression will be evaluated before all others do.

Note:

You can use commas to print more than one expression at once. It beats writing a separate print command for every expression you wish to output. However, for better readability, it is recommended that you will separate your expressions among several prints.

Written by Shlomi Fish