Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: help sorting hash of hashes by value

by kcott (Archbishop)
on Apr 07, 2022 at 08:12 UTC ( [id://11142786]=note: print w/replies, xml ) Need Help??


in reply to help sorting hash of hashes by value

G'day Special_K,

Your basic problem is not taking into account the fact that hashes are unordered. You'll get foo1, foo2 & foo3 returned in a random order when you call keys %hoh_test; and, for each of those, you'll get bar & baz returned in a random order when you call keys %{$hoh_test{$foo}}.

Here's my take on a solution:

#!/usr/bin/env perl use strict; use warnings; my %hoh_test = ( foo1 => { bar => -0.12697, baz => -0.000398154 }, foo2 => { bar => -4.0183e-05, baz => 0 }, foo3 => { bar => 9.966003977e-06, baz => 0.0001939 }, ); my @hoh_data; for my $k0 (keys %hoh_test) { for my $k1 (keys %{$hoh_test{$k0}}) { push @hoh_data, [$k0, $k1, $hoh_test{$k0}{$k1}]; } } my $fmt = "foo: %s, ba: %s, value: %s\n"; printf $fmt, @$_ for sort { $b->[2] <=> $a->[2] } @hoh_data;

This produces the same output on each run:

foo: foo3, ba: baz, value: 0.0001939 foo: foo3, ba: bar, value: 9.966003977e-06 foo: foo2, ba: baz, value: 0 foo: foo2, ba: bar, value: -4.0183e-05 foo: foo1, ba: baz, value: -0.000398154 foo: foo1, ba: bar, value: -0.12697

Just to exemplify the unordered nature of hashes, here's what @hoh_data looked like, on two separate runs, before passing to sort { $b->[2] <=> $a->[2] }:

( ["foo1", "bar", -0.12697], ["foo1", "baz", -0.000398154], ["foo2", "baz", 0], ["foo2", "bar", -4.0183e-05], ["foo3", "baz", 0.0001939], ["foo3", "bar", 9.966003977e-06], )
( ["foo1", "baz", -0.000398154], ["foo1", "bar", -0.12697], ["foo3", "baz", 0.0001939], ["foo3", "bar", 9.966003977e-06], ["foo2", "bar", -4.0183e-05], ["foo2", "baz", 0], )

Update: Well, I made a real mess of keys %{hoh_test($foo}}. Now fixed: keys %{$hoh_test{$foo}}.

— Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11142786]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-25 23:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found