Special_K has asked for the wisdom of the Perl Monks concerning the following question:
I have the following code intended to sort a hash of hashes by value:
#!/usr/bin/perl -w use strict; my %hoh_test; $hoh_test{foo1}{bar} = -0.12697; $hoh_test{foo1}{baz} = -0.000398154; $hoh_test{foo2}{bar} = -4.0183e-05; $hoh_test{foo2}{baz} = 0; $hoh_test{foo3}{bar} = 9.966003977e-06; $hoh_test{foo3}{baz} = 0.0001939; # sort descending by value foreach my $foo (keys(%hoh_test)) { foreach my $ba (sort {$hoh_test{$foo}{$b} <=> $hoh_test{$foo}{$a}} + keys(%{$hoh_test{$foo}})) { printf("foo: $foo, ba: $ba, value: %s\n", $hoh_test{$foo}{$ba} +); } }
Here is the expected output:
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
The actual output varies most times the program is run, so clearly my code doesn't work as intended. My two questions are:
1. How can I fix this to sort by values?
2. What exactly is it even doing now? Given that the output changes with most runs it doesn't appear to be sorting by anything.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: help sorting hash of hashes by value
by graff (Chancellor) on Apr 07, 2022 at 01:10 UTC | |
|
Re: help sorting hash of hashes by value
by kcott (Archbishop) on Apr 07, 2022 at 08:12 UTC | |
|
Re: help sorting hash of hashes by value
by cavac (Prior) on Apr 07, 2022 at 07:07 UTC | |
|
Re: help sorting hash of hashes by value
by atcroft (Abbot) on Apr 08, 2022 at 01:18 UTC | |
|
Re: help sorting hash of hashes by value
by johngg (Canon) on Apr 08, 2022 at 15:40 UTC |