📘 Assignment meta-operator = in Perl 6

The design of the operators in Perl 6 is very consistent. For example, if you add a new operator to the language, Perl 6 will create a few more to keep the harmony. In this section, we will talk about the so-called meta-operators, the operators over other operators.

The assignment meta-operators (=) use the other operators to create the constructions like +=, ~=, etc. The action of the newly created operators is always equivalent to the verbose code.

If you type $a op= $b, then a compiler will execute the following action: $a = $a op $b.

That means that $x += 2 is equivalent to $x = $x + 2, and $str ~= ‘.’ to $str = $str ~ ‘.’.

Let us now create a new custom operator and see if the assignment meta-operator will be available for us. On purpose, I chose quite an outstanding-looking operator ^_^:

sub infix:<^_^>($a, $b) {
    $a ~ '_' ~ $b

First, check the simple usage of the new operator with two operands:

say 4 ^_^ 5; # 4_5

Then, let us try the meta-operator form of it: ^_^=:

my $x = 'file'; 

$x ^_^= 101;
say $x; # file_101

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