Now that you've got the basics of the language down, this secondarticle in the series teaches you about Perl's variables and operators, andalso introduces you to conditional expressions.
As you've already seen in last time's lesson, Perl comes with all the standard arithmetic operators - addition [+], subtraction [-], division [/] and multiplication [*] - and quite a few non-standard ones. Here's an example which demonstrates the important ones:
#!/usr/bin/perl
# get a number
print "Gimme a number! ";
$alpha = <STDIN>;
# get another number
print "Gimme another number! ";
$beta = <STDIN>;
# process input
chomp($alpha);
chomp($beta);
# standard stuff
$sum = $alpha + $beta;
$difference = $alpha - $beta;
$product = $alpha * $beta;
$quotient = $alpha / $beta;
# non-standard stuff
$remainder = $alpha % $beta;
$exponent = $alpha ** $beta;
# display the result
print "Sum: $sum\n";
print "Difference: $difference\n";
print "Product: $product\n";
print "Quotient from division: $quotient\n";
print "Remainder from division: $remainder\n";
print "Exponent: $exponent\n";
As with all other programming languages, division and
multiplication take precedence over addition and subtraction, although parentheses can be used to give a particular operation greater precedence. For example,
#!/usr/bin/perl
print(10 + 2 * 4);
returns 18, while
#!/usr/bin/perl
print((10 + 2) * 4);
returns 48.
In addition to these operators, Perl also
comes with the very useful auto-increment [++] and auto-decrement [--] operators, which you'll see a lot of in the next lesson. For the moment, all you need to know is that the auto-increment operator increments the value of the variable to which it is applied by 1, while the auto-decrement operator does exactly the same thing, but in the opposite direction. Here's an example: