Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: hash of hashes sort second level keys

by rubasov (Friar)
on Feb 19, 2010 at 17:49 UTC ( #824216=note: print w/ replies, xml ) Need Help??


in reply to hash of hashes sort second level keys

If you flatten your data structure, it would be a lot easier to access the sort key wanted. Of course this is not optimal as you need to duplicate all your data in a temporary array.

#! /usr/bin/perl use strict; use warnings; my %h; # if your data is really numerical then the apostrophes are superfluou +s $h{10}{20} = 5; $h{10}{25} = 4; $h{05}{50} = 3; $h{20}{30} = 2; my @temp; for my $key1 ( keys %h ) { for my $key2 ( keys %{ $h{$key1} } ) { # create a 3-column table from your hash push @temp, [ $key1, $key2, $h{$key1}{$key2} ]; } } # sort it by the second column numerically for ( sort { $a->[1] <=> $b->[1] } @temp ) { print 'key1=', $_->[0], ', key2=', $_->[1], ', value=', $_->[2], "\n +"; }
I hope this helps.

update: a little clarification: By using the solution above you need to store every one of your key1, key2 and value at least once more, but in the terms of memory consumption this can be more than a duplicate.


Comment on Re: hash of hashes sort second level keys
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2014-09-21 23:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (176 votes), past polls