📘 Numeric operators div and mod in Perl 6

div is the integer division operator. If the floating point is truncated, the result is rounded to the preceding lower integer.

say 10 div 3;  # 3
say -10 div 3; # -4

mod is another form of the modulo:

say 10 % 3;   # 1
say 10 mod 3; # 1

Unlike the / and % operators, the div and mod forms do not cast the operands to the numeric value. Compare the following two examples.

say 10 % "3"; # 1

With a mod operator, an error occurs:

say 10 mod "3";
Calling 'infix:<mod>' will never work with argument types (Int, Str) 
Expected any of: :(Real $a, Real $b) 

To satisfy the requirements, you may make the type conversion explicitly using either the + prefix operator:

say 10 mod +"3"; # 1

or calling the .Int method:

say 10 mod "3".Int; # 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s