Jason Vorhees
Jason Vorhees

Reputation: 21

Perl loop between two arrays

@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

Upvotes: 0

Views: 608

Answers (2)

Fergal
Fergal

Reputation: 5613

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;

Upvotes: 2

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74232

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.

Upvotes: 2

Related Questions