Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Sorting Multilevel Hashes

by hippo (Bishop)
on Apr 24, 2014 at 22:45 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-03-19 11:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found