Sum the odd and even indices of an array separately – Perl

  • A+
Category:Languages

I have an array of 11 elements. Where I want to sum the odd elements including the first and last elements as one scalar and the evens as another.

This is my code I am trying to use map adding 2 to each index to achieve the result but I think I have got it wrong.

use strict; use warnings; use Data::Dumper;  print 'Enter the 11 digiet serial number: '; chomp( my @barcode = //, <STDIN> );  my @sum1 = map { 2 + $_ } $barcode[1] .. $barcode[11]; my $sum1 = sum Dumper( /@sum1 );  # sum2 = l2 + l4 + l6 + r8 + r10; printf "{$sum1}"; 

What is a good way to achieve this?

 


Sum of even/odd indicies (what you asked for, but not what you want[1]):

use List::Util qw( sum );   # Or: sub sum { my $acc; $acc += $_ for @_; $acc }  my $sum_of_even_idxs = sum grep { $_ % 2 == 0 } 0..$#nums; my $sum_of_odd_idxs  = sum grep { $_ % 2 == 1 } 0..$#nums; 

Sum of even/odd values (what you also asked for, but not what you want[1]):

use List::Util qw( sum );   # Or: sub sum { my $acc; $acc += $_ for @_; $acc }  my $sum_of_even_vals = sum grep { $_ % 2 == 0 } @nums; my $sum_of_odd_vals  = sum grep { $_ % 2 == 1 } @nums; 

Sum of values at even/odd indexes (what you appear to want):

use List::Util qw( sum );   # Or: sub sum { my $acc; $acc += $_ for @_; $acc }  my $sum_of_vals_at_even_idxs = sum @nums[ grep { $_ % 2 == 0 } 0..$#nums ]; my $sum_of_vals_at_odd_idxs  = sum @nums[ grep { $_ % 2 == 1 } 0..$#nums ]; 

Given that you know how many elements you have, you could use the following:

use List::Util qw( sum );   # Or: sub sum { my $acc; $acc += $_ for @_; $acc }  my $sum_of_vals_at_even_idxs = sum @nums[0,2,4,6,8,10]; my $sum_of_vals_at_odd_idxs  = sum @nums[1,3,5,7,9]; 

  1. I included these in case someone needing these lands on this Q&A.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: