【发布时间】:2014-08-14 09:21:46
【问题描述】:
如何添加每个数组的元素呢?
@a1 = (1..5);
@a2 = (1..3);
@a3 = (1..4);
@tar = ("@a1", "@a2", "@a3");
foreach $each(@tar){
@ar = split(' ',$each);
foreach $eac(@ar){
$tot+=$eac;
}
print "$each total is: $tot\n";
}
在这段代码中给出了输出,但后面的总值与前面的总值相加。但我是否期望输出:
1 2 3 4 5 total is: 15
1 2 3 total is: 6
1 2 3 4 total is: 10
【问题讨论】:
-
use List::Util 'sum'; ... my $total = sum @ar; -
您应该始终使用
use strict; use warnings;(尽管它对解决这个特定问题没有帮助)。 -
问题已经得到解答,但您可以通过将@tar 设为数组数组而不是字符串数组来简化一点:
my @tar = (\@a1, \@a2, \@a3);。
标签: perl