在raku中连接`s///`

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

my $w = "Hello world";

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

say $w; # » Hola world

但是我似乎无法写出这样的东西。据我所知,用 的.subst方法做这件事Str太丑了,这种连锁
s///甚至tr///基本上也将成为sed用户等的入门药物。

我的问题是我是否遗漏了某些东西,如果在 raku 中以某种方式可能会出现与此类似的东西。我不是初学者,我无法弄清楚。

回答

你可以使用
with
given

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

andthen

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

或者这个丑陋的建筑

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

  • Using the with, you could also do a post fix to avoid the brackets: `s/Hello/Hola/ && s/world/mundo/ with $w`.
  • specially, then the following works
    `echo hello world | raku -ne 's/hello/hola/; s/world/mundo/; .say' `
    which is just a selling point that gets understressed in the raku community, imho
  • @margolari jubilatious1's suggestion is great if you can hoist the value to the main topic. But if not, you can shave off a few more characters by using the reduction operator: `[&&] s///,s///,s///,… with $foo`.

回答

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

S///在进行多次(连续)替换时,利用 Raku 的非破坏性 运算符通常很有用。在 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;

哈。

https://docs.raku.org/language/regexes#S///_non-corruption_substitution

  • this is also very useful, and looks nice `sedish` too!

以上是在raku中连接`s///`的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>