Perl: Number Crunching - The Positive and the Negative (
Page 4 of 5 )
To make a number a negative number, you simply add the - sign to the left of it. For example, -4 equals, well, negative 4. If we want to make a negative number a positive number, we can say -(-5). This is because two negatives make a positive. Here is how negative and positive numbers work in Perl:
#!/usr/bin/perl
$a = "\n";
print -(-5);
print $a;
print -4 - -2;
print $a;
print -4 - -4;
print $a;
print -4 + 5;
print $a;
print 5 - -6;
print $a;
print +(+5);
print $a;
print 5 - 6;
print $a;
print -5 * 5;
print $a;
print 5 / -5;
The results:
5
-2
0
1
11
5
-1
-25
-1
Your Assignment: Math
In addition to assigning a value to a variable, you can also perform math at the same time. For instance, let's say that we have a variable and we want to increase its value by ten. Here is one way of doing it:
#!/usr/bin/perl
$value = 10;
print $value . "\n";
$value = $value * 10;
print $value;
This assigns the value 10 to the variable $value, prints it, and then takes the amount in the variable and multiplies it by ten, reassigns it, and prints it once more. Resulting in:
10
100
An easier way to do this is with the *= operator:
#!/usr/bin/perl
$value = 10;
print $value . "\n";
$value *= 10;
print $value;
Giving us the same result:
10
100
It may not seem like a huge time saver, but over time it can be.
You can do this with the other math operators as well, like so:
#!/usr/bin/perl
$value = 10;
print $value . "\n";
$value *= 10;
print $value . "\n";
$value +=2;
print $value . "\n";
$value -= 1;
print $value . "\n";
$value /= 2;
print $value . "\n";
$value **= 2;
print $value . "\n";
The result is:
10
100
102
101
50.5
2550.25