in reply to Better assignment to Hash of Arrays

I'd:

use strict; use warnings; use Data::Dump::Streamer; my @class = (40, 40, 40, 183, 183, 259, 244, 503); my @qty = (260, 234, 211, 301, 401, 321, 210, 451); my %bin = map {$_ => [0, 0]} (0, 40, 183, 503, 442, 259, 244); for my $i (0 .. $#class) { my $hkey = $class[$i]; @{$bin{$hkey}} = ($bin{$hkey}[0]+1, $bin{$hkey}[1]+ $qty[$i]); } Dump (\%bin);

Note the use of a Perl for loop in place of the C loop and an array assignment in the for loop. Oh, and keep the scope of variables as small as possible ($hkey is declared inside the loop).


True laziness is hard work

Replies are listed 'Best First'.
Re^2: Better assignment to Hash of Arrays
by AnomalousMonk (Archbishop) on Oct 22, 2009 at 14:25 UTC
    I think I might be inclined to an oH instead of an oA:
    >perl -wMstrict -le "my @class = ( 40, 40, 40, 183, 183, 259, 244, 503); my @qty = (260, 234, 211, 301, 401, 321, 210, 451); my %bin = map { $_ => { class => 0, qty => 0 } } 0, 40, 183, 503, 442, 259, 244 ; for my $i (0 .. $#class) { $bin{ $class[$i] }{class}++; $bin{ $class[$i] }{qty} += $qty[$i]; } for my $key (sort { $a <=> $b } keys %bin) { printf qq{%4d => [%2d, %4d] \n}, $key, @{ $bin{$key} }{ qw(class qty) }; } " 0 => [ 0, 0] 40 => [ 3, 705] 183 => [ 2, 702] 244 => [ 1, 210] 259 => [ 1, 321] 442 => [ 0, 0] 503 => [ 1, 451]
Re^2: Better assignment to Hash of Arrays
by journey (Monk) on Oct 22, 2009 at 02:20 UTC
    Exactly what I was looking for! Nice and Perlish... Thanks for taking the time to provide me with valuable tips. Regards