The Pearls of Raku, Issue 10: the -rw things

In this issue, we’ll discuss three elements in the Raku programming language that have the -rw suffix: substr-rw, return-rw, and take-rw.

In this issue, we’ll discuss three elements in the Raku programming language that have the -rw suffix.

Table of Contents

substr-rw

With a regular substr routine (used as either a method or a function), you get a copy of the substring, which is an immutable value. If you want to modify the original string, you can use substr-rw.

Consider the following two examples of using it:

my $string = 'Hello, World!';

$string.substr-rw(7, 5) = 'Mundo';

my $greeting := $string.substr-rw(0, 5);
$greeting = '¡Hola';

say $string; # ¡Hola, Mundo!

In the first case, we assign the new value to the result of the method call. In the second case, we bind it to a scalar. The original string is modified after both assignments. Notice that the length of the replacement string may differ from the length of the replaced part.

return-rw

You can use return-rw in places where you traditionally use return. But with the longer variant, you actually return the object rather than the value.

sub my-value {
    state $value = 3.14;
    return-rw $value;
}

my-value++;

say my-value; # 4.14

The my-value++ construct modifies the state variable inside the function, so you increment it and with the next function call you get the same container with a modified value.

take-rw

A similar pair exists for take. Use it together with gather, in which case you return the container and you have full access to it, not only to its value.

Examine the following program, where the gather block takes $x and $y.

my $x = 42;
my $y = 2020;

my $data := gather {
    take $x;
    take-rw $y;
};

say $data; # (42 2020), is a Seq

# $data[0]++; # Error
$data[1]++;

say "$x, $y"; # 42, 2021

(Notice that the result is bound to a scalar.)

You cannot modify the value gathered by take $x, but you can do so with what was returned by take-rw $y. For the second variable, the program prints its updates value.

* * *

Find the code of this issue on GitHub and browse for more Raku Pearls.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code