#! perl -slw
use strict;
sub weightedSum {
my( $r, $weight ) = ( @_, 1 );
my $sum = 0;
for ( @$r ) {
if( ref ) {
$sum += weightedSum( $_, $weight + 1 );
}
else {
$sum += $_ * $weight;
}
}
return $sum;
}
my $arrref = [
[1,1,1,1],
[1,1, [2,2] ],
[1, [2, [3,3] ] ]
];
print weightedSum( $arrref );
####
C:\test>1152751
56
####
#! perl -slw
use strict;
use List::Util qw[ reduce ]; $a = $b; ## silence warning
sub weightedSum {
my( $r, $weight ) = ( @_, 1 );
return reduce{
$a += ( ref( $b ) ) ? weightedSum( $b, $weight + 1 ): $b * $weight
} 0, @$r;
}
my $arrref = [
[1,1,1,1],
[1,1, [2,2] ],
[1, [2, [3,3] ] ]
];
print weightedSum( $arrref );