在 raku 中连接 `s///`

Concatenating `s///` in raku

我发现一个巨大的 脚本成瘾者加入 raku 的卖点是 可能有这样的结构

my $w = "Hello world";

$w
  ~~ s/Hello/Hola/
  ~~ s/world/mundo/
  ;

say $w; # » Hola world

不过我好像写不出这样的东西。 据我所知,使用 .subst 方法 Str 太丑了,而这个链接 s/// 甚至 tr/// 基本上都是 sed 用户等

的入门药物

我的问题是我是否遗漏了什么,如果有与此类似的东西 在 raku 中以某种方式是可能的。我不是初学者,我可以 想不通

你可以使用 withgiven

with $w {
    s/Hello/Hola/;
    s/world/mundo/;
}

andthen

$w andthen  s/Hello/Hola/ && s/world/mundo/;

或者这个结构

$_ := $w;
s/Hello/Hola/;
s/world/mundo/;

到目前为止一些优秀的答案(包括评论)。

利用 Raku 的非破坏性 S/// 运算符在进行多次(连续)替换时通常很有用。在 Raku REPL 中:

> my $w = "Hello world";
Hello world
> given $w {S/Hello/Hola/ andthen S/world/mundo/};
Hola mundo
> say $w;
Hello world

一旦您对代码感到满意,就可以将结果分配给新变量:

> my $a = do given $w {S/Hello/Hola/ andthen S/world/mundo/};
Hola mundo
> say $a
Hola mundo

将这个想法更进一步,我编写了以下 'baby Raku' 翻译脚本并将其保存为 Bello_Gallico.p6。好玩到运行!

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