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

Re: Sorting Multilevel Hashes

by hippo (Abbot)
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 cooling their heels in the Monastery: (3)
As of 2018-02-21 21:37 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (288 votes). Check out past polls.