perl6 text substitution on array

con*_*con 11 perl6

I'm trying to apply a text substitution to an entire array.

However, when I try to alter the array, it shows that it only has 1 element, when it should have 26.

An example below in Perl6 REPL:

> my @a = 'a'..'z'
[a b c d e f g h i j k l m n o p q r s t u v w x y z]
> my @a1 = @a.subst(/<[aeiou]>/, 1, :g)
[1 b c d 1 f g h 1 j k l m n 1 p q r s t 1 v w x y z]
> @a1.elems
1#this should be 26
> @a.elems
26
Run Code Online (Sandbox Code Playgroud)

如何更改整个数组中具有文本替换的数组,然后返回数组?

另外:perl6网站已关闭,我无法访问许多手册页:(

Eli*_*sen 16

通过使用>>.超级运算符:这将在列表的每个元素上调用给定方法,并创建调用结果的列表。

my @a = "a".."z";
my @b = @a>>.subst(/ <[aeiou]> /, 1, :g);
dd @a, @b;

# Array @a = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
# Array @b = ["1", "b", "c", "d", "1", "f", "g", "h", "1", "j", "k", "l", "m", "n", "1", "p", "q", "r", "s", "t", "1", "v", "w", "x", "y", "z"]
Run Code Online (Sandbox Code Playgroud)


Bra*_*ert 5

.substStr方法。

这意味着它假定它的第一个参数(倡导者)是Str。如果还不是Str,它将被强制为Str

当您调用.Str数组时,它将所有值与一个空格作为分隔符连接在一起。

my @a = < a b c >;
say @a.perl;       # ["a", "b", "c"]
say @a.Str.perl;   # "a b c"
Run Code Online (Sandbox Code Playgroud)

因此,这三行代码完全相同:

@a.subst(/<[aeiou]>/, 1, :g);
@a.Str.subst(/<[aeiou]>/, 1, :g);
@a.join(" ").subst(/<[aeiou]>/, 1, :g);
Run Code Online (Sandbox Code Playgroud)

Perl6这样做是因为它是一致的。您始终知道,对的单个调用的输出.subst是单个Str。您还知道,该倡导者被视为Str

如果它在数组上做了一些不同的事情,将很难跟踪哪些方法根据那里的发起者及其变化方式而变化。

我们只需要看一下Perl5,就可以知道记住每个函数的不一致之处是多么困难。
(尝试考虑一下Perl5中所有$_默认运行的功能,以及它们在标量与列表上下文中的作用。)


与其调用.subst单个数组值,不如调用它包含的每个值。

有几种方法可以做到这一点:

my @ = @a.map( *.subst(…) )

my @ = @a».subst(…)

my @ = do for @a { .subst(…) }

my @ = @a.duckmap( -> Str $_ { .subst(…) } ) # only change Str's
Run Code Online (Sandbox Code Playgroud)