Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Sorting Multilevel Hashes

by hippo (Monsignor)
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.

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1083692]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2017-04-27 10:10 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (502 votes). Check out past polls.