Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: sorting hash of array of hashes by value

by LanX (Sage)
on Aug 26, 2014 at 19:13 UTC ( #1098652=note: print w/replies, xml ) Need Help??


in reply to sorting hash of array of hashes by value

Hashes can't be sorted b/c they have no order.

But you can keep sorted arrays of keys or values.

Your wish to keep the "path"s of a HoAoH sorted is a strong indication for me that you might wanna check the multi-dim hashes we inherited from Perl4.

Like this you could flatten your data to a 1-dim hash

$hash{$key0,$idx0,$key1}=<some floating point value>

and keep an array of sorted @keys .

Looks far simpler for me! (effectively it's using your concat approach w/o the overhead of the origanal HoAoH)

If you need this more often you might wanna check on tiehash solutions on CPAN to allow sorted hashes by encapsulating the sorted @keys .

HTH =)

Cheers Rolf

(addicted to the Perl Programming Language and ☆☆☆☆ :)

edit

fixed syntax error by 's/;/,/'

Replies are listed 'Best First'.
Re^2: sorting hash of array of hashes by value
by LanX (Sage) on Aug 26, 2014 at 21:25 UTC
    Here a proof of concept: (stealing data from AppleFritter's example)

    #!/usr/bin/perl use strict; use warnings; use feature qw/say/; use Data::Dump qw/pp dd/; my %data = ( "key0.1" => [ { "key1.1" => 3.3, "key1.2" => 17.8, "key1.3" => -2.4, }, { "key1.4" => 5.1, "key1.5" => 13, }, { "key1.6" => -69, "key1.7" => 127, "key1.8" => 2.718, "key1.9" => 3.3, }, ], "key0.2" => [ { "key1.10" => 3.3, "key1.11" => 2.5, }, { "key1.12" => -33, }, ], ); my %flat = (); while (my ($k0,$v0) = each %data) { my $k1=-1; for my $v1 (@$v0) { $k1++; while (my ($k2,$v2) = each %$v1) { $flat{$k0,$k1,$k2} = $v2; } } } my @sorted_keys = sort { $flat{$a} <=> $flat{$b} } keys %flat; for my $k (@sorted_keys) { my $v = $flat{$k}; say "$v \t<= \t", join ", ", split ( $; , $k ); }

    Output:

    HTH! =)

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2021-10-26 22:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (91 votes). Check out past polls.

    Notices?