in reply to Re: How to combine the values from hash using 'cname', along with total and balance.
in thread How to combine the values from hash using 'cname', along with total and balance.
I love a good artifact as much as the next programmer, and this does not even require contiguous cnames.
#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11112008 use warnings; use List::Util qw( uniq ); 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 %temphash; for ( @$aref ) { $temphash{$_->{cname}}{cname} = $_->{cname}; $temphash{$_->{cname}}{balance} += $_->{balance}; $temphash{$_->{cname}}{total}++; } my $answer = [ @temphash{ uniq map $_->{cname}, @$aref } ]; use Data::Dump 'dd'; dd $answer;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: How to combine the values from hash using 'cname', along with total and balance.
by AnomalousMonk (Archbishop) on Jan 30, 2020 at 03:14 UTC | |
|
Re^3: How to combine the values from hash using 'cname', along with total and balance.
by Sami_R (Sexton) on Jan 30, 2020 at 11:37 UTC |