Chapter 4. Loops, Conditionals, and Recursion
The main topic of this chapter is the if statement, which executes different code depending on the state of the program. But first I want to introduce two new operators: integer division and modulo.
Integer Division and Modulo
The integer division operator, div, divides two numbers and rounds down to an integer. For example, suppose the runtime of a movie is 105 minutes. You might want to know how long that is in hours. In Perl, conventional division returns a rational number (in many languages, it returns a floating-point number, which is another kind of internal representation for noninteger numbers):
> my $minutes = 105; > $minutes / 60; 1.75
But we don’t normally write hours with decimal points. Integer division returns the integer number of hours, dropping the fraction part:
> my $minutes = 105; > my $hours = $minutes div 60; 1
In arithmetic, integer division is sometimes called Euclidean division, which computes a quotient and a remainder.
To get the remainder, you could subtract off one hour in minutes:
> my $remainder = $minutes - $hours * 60; 45
An alternative is to use the modulo operator, %, which divides two numbers and returns the remainder:
> my $remainder = minutes % 60; 45
The modulo operator is very common in programming languages and is more useful than it seems. For example, you can check whether one number is divisible by another—if $dividend % $divisor is zero, then $dividend is divisible by $divisor. This is commonly ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access