shadowline
Environments << Common Operators >> Comparison Operators
Ready for some heavy math lesson?

Operators are the calculations that are possible. Adding, subtracting, comparing, etc..

Common operators are the regular math types. Add, subtract, multiply, and divide.
+ - * /

Here is an example. It sets 3 variables to numbers and performs some simple math to them.
#!/usr/bin/perl
print "Content-type: text/html\n\n;
$x = 5;
$y = 15.5;
$z = .05;

$a = $x + $y;
print "a equals $a<br>";

$b = $z + 5;
print "b equals $b<br>";

$c = $x / $z;
print "c equals $c<br>";

$d = $x * $y;
print "d equals $d<br>";

$x = $x + 2.5;
print "x equals $x";

Check out that last equation. The value of $x actually changed during the calculation. On the equation side, it took the current value of $x and added 2.5 to it. The new value is then transferred into the $x variable. Kinda looks like it would put itself into an endless loop doesn't it? Well, PERL seems to be smart enough to know better and allow this. A different way of displaying this equation would be :
$x += 2.5;
Which translated means "Add 2.5 to the current value of $x". Here are some other examples of shorthand math :

$a = ++$y;
$y is increased by 1 before the value is assinged to $a.

$b = $z++;
$b is assinged the value of $z before the $z is increased by 1.

Using two minus signs -- will have the same effect but subtract 1 instead of adding it.

What about using more than one common operator in a single equation?

5 + 2 * 3 = ???

What do you think the result of this equation would be? 11 or 21?

The answer is 11. PERL uses the same principles as normal math. You may have learned about BEDMAS in classes. This stands for :

Brackets Exponents Division Multiplication Addition Subtraction.

These are the rules that show what order things are done in. If the equation has anything in brackets, those will be calculated first, and exponents will be done next, division is next, and so on. So looking at the example question... the 2 mulitply 3 is performed first and then added to 5.

Exponents are multiplying a number to itself many times.
3 raised to the 4th power = 34 = 3*3*3*3 = 81.

Perl uses ** as the exponential operator. The above example would be seen as :

$result = 3 ** 4;

$result holds the value of 81.

Using division will produce remainders. That is the left over amount after the "whole number". If you divide 25 by 7 the whole number is 3 and the remainder is 4. 3*7=21+4=25. Perl has a built in function to find the remainder. It uses the % symbol. (The % symbol is also used for specifying HASH data, but that comes later in the tutorial pages.)

$dividend = 25;
$divisor = 7;
$remainder = $dividend % $divisor;

The $remainder will have the value of 4.
Environments << Common Operators >> Comparison Operators
shadow

Advertise in the banner along the top, Click here!

Valid XHTML 1.0 Transitional Valid CSS! Text Link Ads
shadow
shadow