2

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
3
  • 2
    use List::Util 'sum'; ... my $total = sum @ar; Commented Aug 12, 2014 at 8:16
  • 4
    You should always use use strict; use warnings; (though it won't help with this particular problem). Commented Aug 12, 2014 at 14:27
  • The question has already been answered, but you can simplify a little by making @tar be an array of arrays instead of an array of strings: my @tar = (\@a1, \@a2, \@a3);. Commented Aug 12, 2014 at 17:04

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

If you want $tot's scope to be just inside the loop, just declare it inside the loop:

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

2 Comments

Thank you @choroba abd giw how it is done.? what is the meaning of 'my'. When declare use warnings use strict then only declare the 'my'
@RPbu: my creates a new variable for each iteration of the loop. See my.
0

Some tips:

  1. Always include use strict; and use warnings; in EVERY perl script. No exceptions

  2. Always declare your variables with my and use the smallest scope possible.

  3. Study perldsc - Perl Data Structures Cookbook for alternative ways of working with arrays and array references.

These changes will clean up your script to the followign:

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

Outputs:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.