[Chicago-talk] Combine like hash elements

Alan Mead amead2 at alanmead.org
Mon Nov 23 08:40:54 PST 2015


Richard,

So, you want the new hash to have fewer elements.  There may be an
idiomatic way, but the straightforward way would be to cycle through
your old hash building a new hash of totals. Let's say your hash is
%trans, then:

my %total_trans;
for my $k ( keys %trans) {
  my $name = $$trans{$k}->{'NAME'}; # check if this is right
  my $amount = $$trans{$k}->{'AMOUNT'}; # check if this is right
  $total_trans{$name} += $amount;
}
printf "%.2f\n", $total_trans{'Lincoln Park'}; # prints 38.00

You'll have to check the two temporary variables to ensure I
dereferenced them correctly and then you could factor them out.  You
could modify this so the new hash has the same structure as the old hash.

I think this would be clearer than trying to edit the original hash.
Pity your data are not in a database where this would be a simple
database call.

-Alan


On 11/23/2015 10:10 AM, richard at rushlogistics.com wrote:
> I have a hash reference with the following structure:
>
> {
> '11' => {'AMOUNT' => '20.00','ID' => '11','NAME' => 'Lincoln Park'},
> '12' => {'AMOUNT' => '38.00','ID' => '12','NAME' => 'Bucktown'},
> '13' => {'AMOUNT' => '41.00','ID' => '12','NAME' => 'Lincoln Park'}
> }
>
> Can anyone tell me how I can combine them by 'NAME' so that I would have:
>
> {
> '11' => {'AMOUNT' => '61.00','ID' => '11','NAME' => 'Lincoln Park'},
> '12' => {'AMOUNT' => '38.00','ID' => '12','NAME' => 'Bucktown'},
> }
>
> Thanks
> _______________________________________________
> Chicago-talk mailing list
> Chicago-talk at pm.org
> http://mail.pm.org/mailman/listinfo/chicago-talk

-- 

Alan D. Mead, Ph.D.
President, Talent Algorithms Inc.

science + technology = better workers

+815.588.3846 (Office)
+267.334.4143 (Mobile)

http://www.alanmead.org

Announcing the Journal of Computerized Adaptive Testing (JCAT), a
peer-reviewed electronic journal designed to advance the science and
practice of computerized adaptive testing: http://www.iacat.org/jcat



More information about the Chicago-talk mailing list