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 ifbar
is aScalar
container that contains a string thenfoo => bar
constructs a pair with its value being thatScalar
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 aScalar
container. (After all,%(...)
constructs aHash
, so why not?) But instead you must use aScalar
declarator.The most succinct
Scalar
declarator is for an anonymous stateScalar
using$ = ...
. But @Håkon has usedmy $ = ...
in their answer. Why? Because the{...}
closure called by themap
retains state between calls of it. If you use just$ = ...
then you'd be reusing the sameScalar
container for all the pairs. Instead you needmy $ = ...
to get freshScalar
s 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";