tags:

views:

148

answers:

2

I have an array of array like below with all numeric values. I want to perform some mathematical operations with these values.

1) Add and print the values of each array elements. e.g.

sum $VAR1 = sum1
sum $VAR2 = sum2

2) Add all the values from each variables. e.g.

sum $VAR1 + $VAR2 +...+ $VARn = totalsum

3) Finding percentage of each variable's total (sum1, sum2, etc) with the totalsum.

$VAR1 = [
          '17071',
          '16120',
          '16292',
    'upto n numbers'
        ];
$VAR2 = [
          '1306',
          '1399',
          '1420',
    'upto n numbers'
        ];  
.
.
.
$VARn = [
          '1835',
          '1946',
    'upto n numbers'
        ];

I have tried below code to perform addition of first array ref but its not giving me the correct values.

my $total = 0;
($total+=$_) for $input[0];
print $total;
+7  A: 

I'd do it this way:

use List::Util qw(sum)
my @sums = map { sum(@{$_}) } @array;
my $sum_of_sums = sum(@sums);
my @percentages = map { $_ / $sum_of_sums } @sums;

(edit: In your code, you needed to dereference the arrayref at $input[0].)

Dave Pirotte
+3  A: 

Dave's answer already covers the simple cases. If you want to do large-scale processing with matrixy data, consider using the PDL module. (Specifically, start with PDFL::Intro. Thanks for that, Brad)

tsee
http://search.cpan.org/perldoc/PDL::Intro
Brad Gilbert