gpt4 book ai didi

Perl for循环批量迭代

转载 作者:行者123 更新时间:2023-12-05 03:23:37 25 4
gpt4 key购买 nike

我正在尝试编写一个小的 Perl 脚本,它需要添加 sleep 时间以延迟 for 循环中的执行命令。

这是例子。

use strict;
use warnings;
use v5.26.1;

my $delay = 10;
my $num = 100;

for (my ($i, $d) = (1, $delay); $i <= $num; $i++, $d+=5 ) {

say "delaying iteration $i by $d";
sleep($d);
}

输出也很简单

delaying iteration 1 by 10
delaying iteration 2 by 15
delaying iteration 3 by 20
delaying iteration 4 by 25
delaying iteration 5 by 30

但是我必须增加每 5 次迭代的 sleep 时间示例应该如下所示

前 5 行应该像这样延迟没有 sleep 时间

delaying iteration 1 by 0
delaying iteration 2 by 0
delaying iteration 3 by 0
delaying iteration 4 by 0
delaying iteration 5 by 0

接下来的 5 行应该像这样延迟 5 秒的雨季时间

delaying iteration 6 by 5
delaying iteration 7 by 5
delaying iteration 8 by 5
delaying iteration 9 by 5
delaying iteration 10 by 5

然后每 5 次迭代, sleep 时间应增加 5 秒。

delaying iteration 11 by 10
delaying iteration 12 by 10
delaying iteration 13 by 10
delaying iteration 14 by 10
delaying iteration 15 by 10

有人可以建议如何让它以这种方式工作吗?

最佳答案

然后每 5 次迭代更改延迟,使用 modulo (%) operator例如,根据需要

use warnings;
use strict;
use feature 'say';

my $delay = 0;
my $num = 100;

foreach my $n (1 .. $num) {
say $n;

sleep $delay;

$delay += 5 if $n % 5 == 0; # every 5-th
}

关于Perl for循环批量迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72481856/

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