没有评估的列表重复(xx)?
List repetition (xx) without evaluation?
列表重复运算符 (xx
) 每次重复时都会计算列表。例如,
my @input = get() xx 5;
将评估 STDIN 的前 5 行。有什么办法可以只重复元素的 value 5 次,而不是每次都对其求值吗?目前,我一直在将它分配给一个变量,然后重复它,但这样似乎有点麻烦。
my $firstLine = get();
my @firstlineRepeated = $firstLine xx 5;
是否有前缀或其他东西可以让我在一条语句中做到这一点?
您可以尝试使用 andthen
运算符:
my @input = (get() andthen $_ xx 5);
来自文档:
The andthen
operator returns Empty upon encountering the first
undefined argument, otherwise the last argument. Last argument is
returned as-is, without being checked for definedness at all.
Short-circuits. The result of the left side is bound to $_
for the
right side, or passed as arguments if the right side is a Callable,
whose count must be 0 or 1.
使用 given
将其上下文化为 $_
是一种相当简洁的方法:
my @input = ($_ xx 5 given get());
say @input;
当我输入 hello
时,得到:
[hello hello hello hello hello]
由于 given
只是上下文化,而不是进行任何类型的定义或真值测试,因此作为通用模式,它比 andthen
.
更安全一些
使用短语 ENTER
也可以
my @input = ENTER { get() } xx 5;
列表重复运算符 (xx
) 每次重复时都会计算列表。例如,
my @input = get() xx 5;
将评估 STDIN 的前 5 行。有什么办法可以只重复元素的 value 5 次,而不是每次都对其求值吗?目前,我一直在将它分配给一个变量,然后重复它,但这样似乎有点麻烦。
my $firstLine = get();
my @firstlineRepeated = $firstLine xx 5;
是否有前缀或其他东西可以让我在一条语句中做到这一点?
您可以尝试使用 andthen
运算符:
my @input = (get() andthen $_ xx 5);
来自文档:
The
andthen
operator returns Empty upon encountering the first undefined argument, otherwise the last argument. Last argument is returned as-is, without being checked for definedness at all. Short-circuits. The result of the left side is bound to$_
for the right side, or passed as arguments if the right side is a Callable, whose count must be 0 or 1.
使用 given
将其上下文化为 $_
是一种相当简洁的方法:
my @input = ($_ xx 5 given get());
say @input;
当我输入 hello
时,得到:
[hello hello hello hello hello]
由于 given
只是上下文化,而不是进行任何类型的定义或真值测试,因此作为通用模式,它比 andthen
.
使用短语 ENTER
也可以
my @input = ENTER { get() } xx 5;