Perl 两个数组之间的循环

发布于 2024-10-03 12:45:08 字数 299 浏览 1 评论 0原文

@a1 = qw(1 2 3) 
@a2 = qw(1 2 3 4 5)

寻找 a1 和 a2 之间的计算结果作为 a2[0] 的值插入。例如 1+1 = 2 进入 a2[0] 作为 2,那么下一个计算将是 2+2 (a2[0] + a1[1]) 导致 a2[0] = 4,然后是 4+3 (a2[0]+a1[2]) 导致 a2[0] = 7,然后移至 a2 中的下一行并对 a1 执行相同的函数。

完成所有操作后,结果将来自 print @a2;

7 8 9 10 11

@a1 = qw(1 2 3) 
@a2 = qw(1 2 3 4 5)

looking have the resultant of a calculation between a1 and a2 be inserted as the value of a2[0]. example would be 1+1 = 2 going into a2[0] as 2, then the next calculation would be 2+2 (a2[0] + a1[1]) resulting in a2[0] = 4, then 4+3 (a2[0]+a1[2]) resulting in a2[0] = 7, then move on to the next line in a2 and perform the same function against a1.

when all said and done the result would be from print @a2;

7 8 9 10 11

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

假装爱人 2024-10-10 12:45:08

因此,本质上您是将第一个数组中的值的总和添加到第二个数组中的每个元素。

my $total = 0;
($total += $_) for @a1;
($_ += $total) for @a2;

So essentially you're adding the total of the values in the first array to each element in the second array.

my $total = 0;
($total += $_) for @a1;
($_ += $total) for @a2;
死开点丶别碍眼 2024-10-10 12:45:08

使用相关列表函数:

#!/usr/bin/env perl

use strict;
use warnings;

use List::Util      qw( sum   );
use List::MoreUtils qw( apply );

my @a1 = qw( 1 2 3     );
my @a2 = qw( 1 2 3 4 5 );

my $sum = sum(@a1);

@a2 = apply { $_ += $sum } @a2;

参考:

另请参阅 Fergal的答案,在这种情况下更简单。

Using relevant list functions:

#!/usr/bin/env perl

use strict;
use warnings;

use List::Util      qw( sum   );
use List::MoreUtils qw( apply );

my @a1 = qw( 1 2 3     );
my @a2 = qw( 1 2 3 4 5 );

my $sum = sum(@a1);

@a2 = apply { $_ += $sum } @a2;

Refer:

Also refer Fergal's answer, which is simpler in this case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文