norbdum
norbdum

Reputation: 2491

Perl adding corresponding/respective values of array to variables

I have some scalar values in array

@array=(1,2,3,4,5);

We can directly assign these values to variables as

($a,$b,$c,$d,$e)=@array;

Is there some way so that I can add the corresponding values of @array numbers like $x +=10;

($a,$b,$c,$d,$e) +=@array;

Sorry for asking such silly question ;)

Upvotes: 0

Views: 168

Answers (2)

jkshah
jkshah

Reputation: 11713

Try using map

my @array=(1,2,3,4,5);
my ($a,$b,$c,$d,$e) = map { $_ + 10 } @array;

Upvotes: 1

mvp
mvp

Reputation: 116437

You can sum all elements of array using sum from List::Util:

use List::Util qw(sum);

my $sum = sum(@array);

UPDATE: It seems that you want to add arrays element by element, then you can use pairwise from List::Moreutils:

use List::MoreUtils qw(pairwise);

my @array = qw(10 20 30);
my @incr  = qw( 1  2  3);
pairwise { $a += $b } @array, @incr;   # (11,22,33)

Upvotes: 0

Related Questions