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

my $var = 7;
say -$var; #> -7

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 which use ++ or -- 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:

say [1..10]; #> [1 2 3 4 5 6 7 8 9 10]

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.

my @array = ('first', 'second', 'third' );
say @array[0]; #> 'first'

Here is a variation on the = assignment operator, but only assigns if the right side is defined!

sub infix:< ?= > ($left is rw, $right) { $left = $right if defined $right }
my $var;
my $new ?= $var; # No assignment happens because no value is set for $var yet.
$var = 24;
$new ?= $var; # $new now gets set to 24

The x infix operator usually duplicates a string the specified number of times.

say 13 x 3; #> 131313 # String is duplicated 3 times

If we want, we can redefine x to do multiplication instead!

sub infix:< x >($left, $right) { $left * $right }
say 13 x 3; #> 39 # Now they are multiplied!

Feel free to use full unicode characters. We can make our own three way comparer:

sub infix:<¯\_(ツ)_/¯>($left, $right) { $left <=> $right }
10 ¯\_()_5; #> More
5 ¯\_()_5; #> Same

Let's see some circumfix! Here we use ⟅ ⟆ to reverse each string in the list.

sub circumfix:<⟅ ⟆> ( *@array ) {
        for @array.keys -> $i {
            @array[$i] = @array[$i].flip;
say'cat', 'dog', 'bird'⟆; #> [tac god drib]