【问题标题】:How to add the values of each array in perl?perl中如何将每个数组的值相加?
【发布时间】: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


【解决方案1】:

问题是因为您在每个 foreach 循环中使用了相同的变量 $tot。所以它保留了旧值。简单的解决方法是在每个循环中首先将 $tot 定义为词法变量。

#!/usr/bin/perl
@a1 = (1..5);
@a2 = (1..3);
@a3 = (1..4);
@tar = ("@a1", "@a2", "@a3");
foreach $each(@tar){
        my $tot;
        @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

【讨论】:

    【解决方案2】:

    如果你想让 $tot 的作用域刚好在循环内,只需在循环内声明它:

    for $each (@tar) {
        my $tot;
    

    【讨论】:

    • 谢谢@choroba abd giw 它是如何完成的。? “我的”是什么意思。当声明使用警告使用严格时,只声明'我的'
    • @RPbu: my 为循环的每次迭代创建一个新变量。见my
    【解决方案3】:

    一些提示:

    1. 在每个 perl 脚本中始终包含 use strict;use warnings;。没有例外

    2. 始终使用my 声明变量并尽可能使用最小的范围。

    3. 研究perldsc - Perl Data Structures Cookbook,了解使用数组和数组引用的替代方法。

    这些更改会将您的脚本清理为以下内容:

    use strict;
    use warnings;
    
    my @a1 = (1..5);
    my @a2 = (1..3);
    my @a3 = (1..4);
    
    my @AoA = (\@a1, \@a2, \@a3);
    
    for my $arrayref (@AoA){
        my $total = 0;
        for my $val (@$arrayref) {
            $total += $val;
        }
        print "@$arrayref total is: $total\n";
    }
    

    输出:

    1 2 3 4 5 total is: 15
    1 2 3 total is: 6
    1 2 3 4 total is: 10
    

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 2021-08-15
      相关资源
      最近更新 更多