in reply to Re: Hash sorting
in thread Hash sorting

Perhaps we should code up a generic solution.
(UNTESTED) sub tree_paths { my $tree = shift; # assumes hashref map { my $k = $_; my $v = $tree->{$k}; ref $v ? map( [ $k, @$_ ], tree_paths( $v ) ) : [ $k, $v ] } keys %$tree } # now use it with the OP's $hash hashref print "Count Section Item\n"; for ( sort { $b->[2] <=> $a->[2] # count or $a->[0] cmp $b->[0] # section or $a->[1] cmp $b->[1] # item } tree_paths($hash) ) { my( $section, $item, $count ) = @$_; printf "%5d %7s %7s\n", $count, $section, $item; }
Or perhaps we'd like records with named members:
(UNTESTED) sub tree_tuples { my( $tree, @names ) = @_; my $name = shift @names; map { my $k = $_; my $v = $tree->{$k}; ref $v ? map( +{ $name => $k, %$_ }, tree_tuples( $v, @names ) ) : { $name => $k, $names[0] => $v } } keys %$tree } # now use it with the OP's $hash hashref print "Count Section Item\n"; for ( sort { $b->{'count'} <=> $a->{'count'} or $a->{'section'} cmp $b->{'section'} or $a->{'item'} cmp $b->{'item'} } tree_tuples( $hash, qw( section item count ) ) ) { printf "%5d %7s %7s\n", @{$_}{qw( count section item )}; }

jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.