User-defined operators
Perl 6 allows creating new operators. Unlike, for example, C++, new operators are not restricted to the predefined list of existing operators. You are free to name the operators as you want and choose a new combination of characters.
A user-defined operator should belong to one of the preceding-mentioned categories, such as infix, prefix, or circumfix, and so on.
Let's start with creating a new infix operator, +%
, which calculates the sum of two numeric operands, but the result does not exceed 100:
sub infix:<+%>($a, $b) { my $sum = $a + $b; return $sum < 100 ?? $sum !! 100; }
Defining an operator is similar to creating a subroutine, but the name of it should contain the name of the category and the operator itself.
It is now time to test the just created +%
operator:
say 10 +% 20; # 30 say 40 +% 70; # 100
Another expressive example is an operator for factorial. In mathematics, a factorial is indicated by the exclamation mark after the value. This is also...