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;
  • Comment on Re^2: How to combine the values from hash using 'cname', along with total and balance.
  • Download Code

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

    Oh, neat! Very neat! I should clarify that my solution does not require contiguous 'cname's, but does not detect non-contiguous ones in a data validation sense.


    Give a man a fish:  <%-{-{-{-<

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

    Thank you so much for the different approach.