See Original text in context
method substr-rw(Allomorph \SELF: = 0, = Whatever)
Calls Str.substr-rw
on the invocant's Str
value.
See Original text in context
multi method substr-rw(|) is rwmulti sub substr-rw(|) is rw
Coerces the invocant (or in the sub form, the first argument) to Str, and calls Str.substr-rw with the arguments.
See Original text in context
method substr-rw(, = *)
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. If not specified, $length
defaults to the length of the string.
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 = "abc";.substr-rw(1, 1) = "z";.say; # OUTPUT: «azc»
Note that new characters can be inserted as well:
my = 'azc';.substr-rw(2, 0) = "-Zorro-"; # insert new characters BEFORE the character at index 2.say; # OUTPUT: «az-Zorro-c»
substr-rw
also has a function form, so the above examples can also be written like so:
my = "abc";substr-rw(, 1, 1) = "z";.say; # OUTPUT: «azc»substr-rw(, 2, 0) = "-Zorro-";.say; # OUTPUT: «az-Zorro-c»
It is also possible to alias the writable reference returned by substr-rw
for repeated operations:
my = "A character in the 'Flintstones' is: barney";~~ /(barney)/;my := substr-rw(, $0.from, $0.to-$0.from);.say;# OUTPUT: «A character in the 'Flintstones' is: barney»= "fred";.say;# OUTPUT: «A character in the 'Flintstones' is: fred»= "wilma";.say;# OUTPUT: «A character in the 'Flintstones' is: wilma»