in reply to performing a function on corresonding array elements

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @set = ( { 'id' => '1462', 'items' => [ '9.9', '10.1', '10.3', '10.5', '10.8', '10.94' ], }, { 'id' => '1463', 'items' => [ '3.1', '4.3', '4.5', '4.6', '4.7', '4.8' ], } ); my @totals; for my $href ( @set ) { $totals[ $_ ] += $href->{items}[ $_ ] for 0 .. $#{ $href->{items} +}; } print Dumper \@totals; __END__ C:\test>540833 $VAR1 = [ '13', '14.4', '14.8', '15.1', '15.5', '15.74' ];

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: performing a function on corresonding array elements
by codeacrobat (Chaplain) on Apr 03, 2006 at 06:23 UTC
    Or more beautiful this way:
    use List::Util qw(sum); ... for my $href ( @set ) { $totals[ $_ ] += sum @{ $href->{items} } } ...
    It makes operations on deeply nested structures a bit more readable.

      It would be beautiful if it worked--but it does not. Where do you set the value of $_?


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
Re^2: performing a function on corresonding array elements
by vindaloo (Acolyte) on Apr 03, 2006 at 02:29 UTC
    Thanks, This is perfect. I appreciate using the original data structure too, that is better than transforming to arrays - (retain my id's). Cheers