Sami_R has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I have hash with three different values for 'cname' 1. 'Smart Parking' 2. 'Highview Parking' and 3. 'ParkingEye', based on the 'cname' need to group it with number count and 'balance' values added.

Please give me directions to achieve this. Thanks

#!/usr/bin/perl -w use strict; use warnings; 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, }, ];

# Expected output

$VAR1 = [ { 'cname' => 'Smart Parking', 'balance' => '30.66', 'total' => '3', }, { 'cname' => 'Highview Parking', 'balance' => '81.08', 'total' => '4', }, { 'cname' => 'ParkingEye', 'balance' => '60.34', 'total' => '2', } ];

Thank you so much

Replies are listed 'Best First'.
Re: How to combine the values from hash using 'cname', along with total and balance.
by hippo (Archbishop) on Jan 29, 2020 at 14:07 UTC

    How do you expect a balance of 30.76 when summing 10.12, 10.22 and 10.32? Either your input is wrong or your output is wrong or your spec of the task is wrong.

    The whole thing seems highly related to How to loop through hash of hashes and add the values based on condition? - have you tried applying what you learned there to this task? What code have you written for this? Where are you stuck?

      Apologies, for providing wrong output.

        Thank you for correcting your post, but please update your OP to note that a correction has been made. Please see How do I change/delete my post?


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

Re: How to combine the values from hash using 'cname', along with total and balance.
by NetWallah (Canon) on Jan 29, 2020 at 17:37 UTC
    Suggestions:

    • Create a temp structure for the result: my %tmp_rslt=(); Key is the 'cname' value, value is a hashref containing 'count' and 'total'
    • Loop through each item in @$aref
    • add to the appropriate cname in %tmp_rslt
    • When complete, loop through %tmp_rslt and create the desired array-ref

                    "From there to here, from here to there, funny things are everywhere." -- Dr. Seuss

      Thanks for the direction

Re: How to combine the values from hash using 'cname', along with total and balance.
by AnomalousMonk (Archbishop) on Jan 30, 2020 at 01:07 UTC

    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.)

    Note that no attempt is made to detect (update: in the sense of data validation) an input lot name that is not contiguous with all others of the same name. (Update: This solution does not require contiguous input lot names. The order of the first appearance of a lot name in the input will be the order of its appearance in the output.)


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

      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;

        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:  <%-{-{-{-<

        Thank you so much for the different approach.

Re: How to combine the values from hash using 'cname', along with total and balance.
by Fletch (Bishop) on Jan 29, 2020 at 17:38 UTC

    Do this, but in perl.

    $ cat ~/fooble.clj (require '[clojure.data.json :as j]) (def data [{"balance" 10.12 "cname" "Smart Parking"} {"balance" 10.22 "cname" "Smart Parking"} {"balance" 10.32 "cname" "Smart Parking"} {"balance" 20.12 "cname" "Highview Parking"} {"balance" 20.22 "cname" "Highview Parking"} {"balance" 20.32 "cname" "Highview Parking"} {"balance" 20.42 "cname" "Highview Parking"} {"balance" 30.12 "cname" "ParkingEye"} {"balance" 30.22 "cname" "ParkingEye"}]) (println (j/write-str (map (fn [[k v]] (merge {:cname k} v)) (reduce (fn [acc {:strs [cname balance]}] (-> acc (assoc-in [cname :balance] (+ balance (get-in acc + [cname :balance] 0))) (assoc-in [cname :total] (inc (get-in acc [cname +:total] 0))))) {} data)))) $ lein run -m clojure.main ~/fooble.clj [{"cname":"Smart Parking","balance":30.66,"total":3},{"cname":"Highvie +w Parking","balance":81.08000000000001,"total":4},{"cname":"ParkingEy +e","balance":60.34,"total":2}]

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: How to combine the values from hash using 'cname', along with total and balance.
by tybalt89 (Monsignor) on Jan 29, 2020 at 18:37 UTC
    #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11112008 use warnings; 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 = [ values %$temphash ]; use Data::Dump 'dd'; dd $answer;

    Outputs:

    [ { balance => 60.34, cname => "ParkingEye", total => 2 }, { balance => 81.08, cname => "Highview Parking", total => 4 }, { balance => 30.66, cname => "Smart Parking", total => 3 }, ]

      Thank you so much

Re: How to combine the values from hash using 'cname', along with total and balance.
by NetWallah (Canon) on Jan 30, 2020 at 19:59 UTC
    Here is a potentially scalable approach using an in-memory SQLITE database:
    use strict; use warnings; use Data::Dumper qw(Dumper); use DBI; 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 $dbh = DBI->connect("dbi:SQLite:dbname=:memory:"); $dbh->do("CREATE TABLE parking ( cname TEXT, balance REAL )"); for my $row (@$aref){ $dbh->do("INSERT INTO parking (cname,balance) VALUES ('$row->{cname +}',$row->{balance})"); } my $sth = $dbh->prepare("SELECT cname, sum(balance) as balance, count( +*) as count FROM parking GROUP BY cname ORDER BY cname"); $sth->execute; my $result ; while (my $r = $sth->fetchrow_hashref()) { push @$result, { balance => $r->{balance}, cname => $r->{cname}, t +otal => $r->{count} } } print Dumper $result;
    It produces:
    $VAR1 = [ { 'balance' => '81.08', 'total' => 4, 'cname' => 'Highview Parking' }, { 'balance' => '60.34', 'total' => 2, 'cname' => 'ParkingEye' }, { 'balance' => '30.66', 'total' => 3, 'cname' => 'Smart Parking' } ];
    Plenty of room for making it more robust and improving performance .. left as an exercise.

                    "From there to here, from here to there, funny things are everywhere." -- Dr. Seuss

      Thank you