Multiplicative Operators

Perl provides the C-like operators * (multiply), / (divide), and % (modulo). The * and / work exactly as you would expect, multiplying or dividing their two operands. Division is done in floating point, unless you've used the integer pragmatic module.

The % operator converts its operands to integers before finding the remainder according to integer division. (However, it does this integer division in floating point if necessary, so your operands can be up to 15 digits long on most 32-bit machines.) Assume that your two operands are called $a and $b. If $b is positive, then the result of $a % $b is $a minus the largest multiple of $b that is not greater than $a (which means the result will always be in the range 0 .. $b-1). If $b is negative, then the result of $a % $b is $a minus the smallest multiple of $b that is not less than $a (which means the result will be in the range $b+1 .. 0).

When use integer is in scope, % gives you direct access to the modulus operator as implemented by your C compiler. This operator is not well defined for negative operands, but will execute faster.

Binary x is the repetition operator. Actually, it's two operators. In scalar context, it returns a concatenated string consisting of the left operand repeated the number of times specified by the right operand. (For backward compatibility, it also does this in list context if the left argument is not in parentheses.)

print '-' x 80; # print row of dashes print "\t" x ($tab/8), ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.