#! 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 );