in reply to How to combine the values from hash using 'cname', along with total and balance.
You have a general approach from NetWallah and a specific impelmentation of that approach from tybalt89.
One detail of the OP is that the order of the lots (I assume these are parking lot names) in the output array seems to reflect the order of groups of lot names in the input array. If this is an actual requirement and not just an artifact of the OPed example, here's an approach to achieving this ordering. (Update: See tybalt89's solution for a much cleaner approach.)
c:\@Work\Perl\monks>perl -le "use strict; use warnings; ;; use Test::More 'no_plan'; use Test::NoWarnings; ;; use Data::Dump qw(dd); ;; my $aref = [ { 'cname' => 'Smart Parking', 'balance' => 10.12, }, { 'cname' => 'Smart Parking', 'balance' => 10.22, }, { 'cname' => 'Smart Parking', 'balance' => 10.32, }, { 'cname' => 'Highview Parking', 'balance' => 20.12, }, { 'cname' => 'Highview Parking', 'balance' => 20.22, }, { 'cname' => 'Highview Parking', 'balance' => 20.32, }, { 'cname' => 'Highview Parking', 'balance' => 20.42, }, { 'cname' => 'ParkingEye', 'balance' => 30.12, }, { 'cname' => 'ParkingEye', 'balance' => 30.22, }, ]; ;; my %lot_and_order; my %merged; for my $hr (@$aref) { my $lot_name = $hr->{'cname'}; $lot_and_order{$lot_name} = keys %lot_and_order unless exists $lot_and_order{$lot_name}; $merged{$lot_name}{'balance'} += $hr->{'balance'}; $merged{$lot_name}{'total'}++; } dd 'merged', \%merged; dd 'lot and order', \%lot_and_order; ;; my @out = map { { 'cname' => $_, 'balance' => $merged{$_}{'balance'}, 'tot +al' => $merged{$_}{'total'} } } map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, $lot_and_order{$_} ] } keys %lot_and_order ; dd 'in lot order', \@out; ;; my $ar_expected = [ { 'cname' => 'Smart Parking', 'balance' => '30.66', 'total' => '3', }, { 'cname' => 'Highview Parking', 'balance' => '81.08', 'total' => '4', }, { 'cname' => 'ParkingEye', 'balance' => '60.34', 'total' => '2', }, ]; ;; is_deeply \@out, $ar_expected, 'merged in lot order'; ;; done_testing; exit; " ( "merged", { "Highview Parking" => { balance => "81.08", total => 4 }, ParkingEye => { balance => "60.34", total => 2 }, "Smart Parking" => { balance => "30.66", total => 3 }, }, ) ( "lot and order", { "Highview Parking" => 1, ParkingEye => 2, "Smart Parking" => 0 }, ) ( "in lot order", [ { balance => "30.66", cname => "Smart Parking", total => 3 }, { balance => "81.08", cname => "Highview Parking", total => 4 }, { balance => "60.34", cname => "ParkingEye", total => 2 }, ], ) ok 1 - merged in lot order 1..1 ok 2 - no warnings 1..2
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to combine the values from hash using 'cname', along with total and balance.
by tybalt89 (Monsignor) on Jan 30, 2020 at 01:33 UTC | |
by AnomalousMonk (Archbishop) on Jan 30, 2020 at 03:14 UTC | |
by Sami_R (Sexton) on Jan 30, 2020 at 11:37 UTC |