Perl 6 makes it easy to define your own operators. Here you will see how you can make your own operators in Perl 6! To get started lets first discuss the different types of operators in Perl 6: infix, prefix, postfix, circumfix and postcircumfix.
What the hell is a circumfix?
Probably the one you are most familiar with is
infix. This is the type of
operator we know well from its use in the standard notation for addition,
subtraction and multiplication:
5 * 8 is infix.
7 + 4 is infix.
9 ÷ 3 is infix.
In fact, in Perl 6, we can actually do
9 ÷ 3 and it will do the division!
What about prefix?
You are probably most familiar with using a
- sign to note a negative value
In Perl 6 this is using the
- prefix operator and will make the number after
it negative. This is also prefix if you are familiar with programming languages
-- to increase or decrease the value of the variable by one:
++$variable; Increments the variable by one and returns the new value.
This can also be used as postfix but slightly different functionality:
$variable++ This increments the variable by one and returns the original value.
Now onto circumfix and postcircumfix. Circumfix goes at the start and the end.
For example we can use the list constructor
[..] to create an list/array like so:
Postcircumfix is similar, but it goes immediately after something. We use a postcircumfix operator to access elements of a list. Notice how in the example below it comes after the variable with no spaces. That is how postcircumfix works.
Here is a variation on the
= assignment operator, but only assigns if the right side is defined!
x infix operator usually duplicates a string the specified number of times.
If we want, we can redefine
x to do multiplication instead!
Feel free to use full unicode characters. We can make our own three way comparer:
Let's see some circumfix! Here we use
⟅ ⟆ to reverse each string in the list.