Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Sorting Multilevel Hashes

by hippo (Curate)
on Apr 24, 2014 at 22:45 UTC ( #1083692=note: print w/ replies, xml ) Need Help??


in reply to Sorting Multilevel Hashes

To my eyes that code is bordering on unmaintainable. If you are attempting to sort by key at each level in turn (which is what I think you are doing - correct me if that isn't the case) then think about recursion. Applying the relevant FAQ (which also discusses sorting by value) just once in a recursive subroutine should do the trick without resorting to $foo{$bar}{$baz}{$quux}{$frob} constructs.


Comment on Re: Sorting Multilevel Hashes
Download Code
Re^2: Sorting Multilevel Hashes
by newCoder (Initiate) on Apr 24, 2014 at 23:00 UTC

    thats right . I want to sort by keys first and then value. It works fine when I do not attempt to add a sort by value. If you could provide an example of how to sort by value in this kind of hash I would really appreciate it.

      Here's an example of sorting by key using recursion.

      #!/usr/bin/perl -Tw # # Multi-level hash sort use strict; use warnings; my %timing1 = initmyhash(); printsortedhash (\%timing1, ''); exit; sub initmyhash { # Obviously, put whatever sets up your hash here. return ( dog => 'rover', cat => { name => 'sandy', age => 10 } ); } sub printsortedhash { my ($this, $report) = @_; for my $key (sort keys %$this) { if (ref $this->{$key} eq 'HASH') { printsortedhash ($this->{$key}, $report . "\t $key") } else { print $report . "\t $key\t $this->{$key}\n"; } } }

      The FAQ linked above shows how to sort by value instead/also. Take your pick.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2014-09-30 22:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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











    Results (385 votes), past polls