I find that a huge selling point for scripting addicts to join raku would be having such constructs possible
my $w = "Hello world";
$w
~~ s/Hello/Hola/
~~ s/world/mundo/
;
say $w; # » Hola world
However I don't seem to be able to write something like this.
As far as I know doing this with the .subst
method
of Str
would be too ugly, and this chaining of
s///
or even also tr///
basically would be
a gateway drug for sed
users etc.
My question is if I'm missing something, if something remotely similar to this is possible somehow in raku. I'm not a beginner and I could not figure it out.
You could use
with
or given
with $w {
s/Hello/Hola/;
s/world/mundo/;
}
andthen
$w andthen s/Hello/Hola/ && s/world/mundo/;
or this ugly construction
$_ := $w;
s/Hello/Hola/;
s/world/mundo/;
Some excellent answers so far (including comments).
Utilizing Raku's non-destructive S///
operator is often useful when doing multiple (successive) substitutions. In the Raku REPL:
> my $w = "Hello world";
Hello world
> given $w {S/Hello/Hola/ andthen S/world/mundo/};
Hola mundo
> say $w;
Hello world
Once you're happy with your code, you can assign the result to a new variable:
> my $a = do given $w {S/Hello/Hola/ andthen S/world/mundo/};
Hola mundo
> say $a
Hola mundo
Taking this idea a little further, I wrote the following 'baby Raku' translation script and saved it as Bello_Gallico.p6
. It's fun to run!
my $caesar = "Gallia est omnis divisa in partes tres";
my $trans1 = do given $caesar {
S/Gallia/Gaul/ andthen
S/est/is/ andthen
S/omnis/a_whole/ andthen
S/divisa/divided/ andthen
S/in/into/ andthen
S/partes/parts/ andthen
S/tres/three/
};
put $caesar;
put $trans1;
HTH.
https://docs.raku.org/language/regexes#S///_non-destructive_substitution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With