gpt4 book ai didi

raku - Perl 6中触发器运算符的使用

转载 作者:行者123 更新时间:2023-12-04 13:18:28 25 4
gpt4 key购买 nike

我看到使用 flip-flop在 doc.perl6.org 中,请参阅以下代码:

my $excerpt = q:to/END/;
Here's some unimportant text.
=begin code
This code block is what we're after.
We'll use 'ff' to get it.
=end code
More unimportant text.
=begin code
I want this line.
and this line as well.
HaHa
=end code
More unimport text.
=begin code
Let's to go home.
=end code
END

my @codelines = gather for $excerpt.lines {
take $_ if "=begin code" ff "=end code"
}

# this will print four lines, starting with "=begin code" and ending with
# "=end code"

.say for @codelines;
=begin code
This code block is what we're after.
We'll use 'ff' to get it.
=end code
=begin code
I want this line.
and this line as well.
HaHa
=end code
=begin code
Let's to go home.
=end code

我想保存 =begin code 之间的行和 =end code到单独的数组中,例如:
['This code block is what we're after.', 'We'll use 'ff' to get it.']
['I want this line.', 'and this line as well.', 'HaHa']
['Let's to go home.']

我知道语法可以做到这一点,但我想知道是否有更好的方法?

最佳答案

您需要指定不包含匹配的值。您可以通过添加 ^ 来做到这一点。到您要排除的运算符的一侧。在这种情况下,它是运营商的双方。

您还需要收集值以将它们组合在一起。在这种情况下,最简单的方法是在比赛之间推迟。
(如果您希望包含端点,则需要更多考虑才能正确处理)

my @codelines = gather {
my @current;

for $excerpt.lines {

if "=begin code" ^ff^ "=end code" {

# collect the values between matches
push @current, $_;

} else {
# take the next value between matches

# don't bother if there wasn't any values matched
if @current {

# you must do something so that you aren't
# returning the same instance of the array
take @current.List;
@current = ();
}
}
}
}

如果您需要结果是数组数组(可变)。

if @current {
take @current;
@current := []; # bind it to a new array
}

另一种方法是使用 do for具有共享相同迭代器的序列。
这是有效的,因为 formap更热心将是。

my $iterator = $excerpt.lines.iterator;

my @codelines = do for Seq.new($iterator) {
when "=begin code" {
do for Seq.new($iterator) {
last when "=end code";
$_<> # make sure it is decontainerized
}
}
# add this because `when` will return False if it doesn't match
default { Empty }
}
map获取一个序列并将其转换为另一个序列,但在您尝试从序列中获取下一个值之前不会执行任何操作。 for立即开始迭代,只有在您告诉它时才停止。

所以 map即使在单个线程上运行也会导致竞争条件,但是 for惯于。

关于raku - Perl 6中触发器运算符的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49280568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com