How do I add the values ​​for each table in Perl?

advertisements

Add the elements of each array how can it.?

@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";
}

In this bit of code gives output but the succeeding total value is add with preceding total value. But is I expect the outputs:

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


The issue is because you are using same variable $tot in each foreach loop. So it retains the old value. Simple fix is to define the $tot as lexical variable in first for each loop.

#!/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";
}

Output is

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