Ways to get mutable strings from a Match object's chunks?

A few things to unpick here:

  • All strings in P6 are immutable. (Thanks Liz. :)) But you probably don't mean you want to get a mutable string. You probably just mean having strings in containers so the contents of those containers can be changed.

  • The => pair constructor does not decontainerize its right hand value if it's in a container. So if bar is a Scalar container that contains a string then foo => bar constructs a pair with its value being that Scalar container containing that string.

  • $(...) is used to parenthesize an expression that is to be treated as singular even if is a plural container. (This mirrors @(...) which is used to parenthesize an expression that is to be treated as plural even if it is a singular container or value.)

  • It's not surprising that you thought $(...) would construct a Scalar container. (After all, %(...) constructs a Hash, so why not?) But instead you must use a Scalar declarator.

  • The most succinct Scalar declarator is for an anonymous state Scalar using $ = .... But @Håkon has used my $ = ... in their answer. Why? Because the {...} closure called by the map retains state between calls of it. If you use just $ = ... then you'd be reusing the same Scalar container for all the pairs. Instead you need my $ = ... to get fresh Scalars for each pair's value.


You can put the immutable string into a scalar container by doing:

my @n = map { $_.key => my $ = $_.value.Str }, G::parse($str).chunks;

then you can later modify the content of the scalar container (but not the content of the string):

@n[0].value = "Hello";

Tags:

Raku