in reply to Iterating elements at different level
The easiest way to process data structures of variable depth and complexity is recursion:
#! 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 );
Produces:
C:\test>1152751 56
A variation:
#! 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 * $we +ight } 0, @$r; } my $arrref = [ [1,1,1,1], [1,1, [2,2] ], [1, [2, [3,3] ] ] ]; print weightedSum( $arrref );
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Iterating elements at different level
by Lennotoecom (Pilgrim) on Jan 12, 2016 at 16:39 UTC |