Documentation for method substr-rw

Documentation for method substr-rw, assembled from the following types:

class Str

From Str

(Str) method substr-rw

method substr-rw($from$length?)

A version of substr that returns a Proxy functioning as a writable reference to a part of a string variable. Its first argument, $from specifies the index in the string from which a substitution should occur, and its last argument, $length specifies how many characters are to be replaced.

For example, in its method form, if one wants to take the string "abc" and replace the second character (at index 1) with the letter "z", then one does this:

my $string = "abc";
$string.substr-rw(11= "z";
$string.say;                         # OUTPUT: «azc␤» 

Note that new characters can be inserted as well:

my $string = 'azc';
$string.substr-rw(20= "-Zorro-"# insert new characters BEFORE the character at index 2 
$string.say;                         # OUTPUT: «az-Zorro-c␤» 

substr-rw also has a function form, so the above examples can also be written like so:

my $string = "abc";
substr-rw($string11= "z";
$string.say;                          # OUTPUT: «azc␤» 
substr-rw($string20= "-Zorro-";
$string.say;                          # OUTPUT: «az-Zorro-c␤» 

It is also possible to alias the writable reference returned by substr-rw for repeated operations:

my $string = "A character in the 'Flintstones' is: barney";
$string ~~ /(barney)/;
my $ref := substr-rw($string$0.from$0.to);
$string.say;
# OUTPUT: «A character in the 'Flintstones' is: barney␤» 
$ref = "fred";
$string.say;
# OUTPUT: «A character in the 'Flintstones' is: fred␤» 
$ref = "wilma";
$string.say;
# OUTPUT: «A character in the 'Flintstones' is: wilma␤» 

Notice that the start position and length of string to replace has been specified via the .from and .to methods on the Match object, $0. It is thus not necessary to count characters in order to replace a substring, hence making the code more flexible.