Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating `s///` in raku

Tags:

raku

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.

like image 701
margolari Avatar asked Nov 29 '20 23:11

margolari


2 Answers

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/;
like image 68
wamba Avatar answered Nov 19 '22 00:11

wamba


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

like image 7
jubilatious1 Avatar answered Nov 18 '22 22:11

jubilatious1