Perl Tutorial

Page 61

4.2 Description of some Operators

49

If $b is negative, the value returned is $a minus the largest integral multiple of $b such that the result is still negative. For example, 63 % -5 = -2 (63 = (−13) × (−5) + (−2), the largest multiple in this case is −13) -63 % -5 = -3 (−63 = 12 × (−5) + (−3), the largest multiple in this case is 12) Such behaviours are so tedious that most programmers simply use the modulus operator for the first case — where both operands are positive integers, which evaluates to the remainder of $a / $b. The positive/negative signs, just as in our usual mathematics, are unary operators that are affixed before a number to indicate whether it is positive or negative. Our usual convention is that the unary positive sign is not specified, because it is the default as expected. If you know C/C++, the autoincrement and the autodecrement operators are identical to what you have learned. For those who don’t know, it’s worth to spend a few minutes to repeat all the details here. These operators can be placed before or after a variable. There are four possible variations: Expression ++$var $var++ --$var $var--

Description Prefix Increment Postfix Decrement Prefix Decrement Postfix Decrement

The first two are autoincrement, while the remaining two are autodecrement. If autoincrement/autodecrement is performed as a statement on its own, the prefix or postfix configurations do not produce any difference. For example, both ++$a; and $a++; as standalone statements increase the value of $a by 1. However, they are different if the operators are used as part of a statement. Consider the following examples:

A. B.

$b = ++$a; $b = $a++;

In statement A, $a is first incremented, and then the new value is returned. In statement B, however, the value is returned first, and then $a is incremented. Therefore, the value returned (and is thus assigned to $b) is the value before increment. The two forms differ in the order of increment/decrement and return of value. Autodecrement works in the same way, except the variable is decremented instead. In other words, statement A and statement B are identical in effect as the following respectively:

++$a; $b = $a; $b = $a; ++$a;

# equivalent to statement A # equivalent to statement B

The exponentiation operator calculates the n th power of a number. For example, 43 , i.e. 4*4*4 is expressed by 4**3, and the result is 64. Both operands can be floating point numbers. All the operands discussed in this section take on scalar values only. In other words, they create a scalar context for the operands.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.