Here's a more generic way to flatten a hash with an arbitrary number of levels. It can be easily extended to handle embedded array refs, as well:

#!/usr/bin/perl -w use strict; my %hash = ( APP1 => { error => { 6001 => 10, 6002 => 15, 6003 => 25, }, alert => { 1001 => 2, 1005 => 200, }, warning => { '0022' => 10, }, }, APP2 => { error => { 6001 => 4, 6004 => 21, }, alert => { 1002 => 3, 1005 => 165, }, }, ); my $separator = '.'; sub flattenHash { my $hashRef = shift; my $prefixArrayRef = shift || []; my $outputArrayRef = shift || []; while ( my ( $key, $value ) = each(%$hashRef) ) { push @$prefixArrayRef, $key; if ( UNIVERSAL::isa( $value, 'HASH' ) ) { flattenHash( $value, $prefixArrayRef, $outputArrayRef ); } else { push ( @$outputArrayRef, join ( $separator, @$prefixArrayR +ef ), $value ); } pop @$prefixArrayRef; } return wantarray ? @$outputArrayRef : $outputArrayRef; } my %flatHash = flattenHash( \%hash ); my @sorted = sort { $b->[0] <=> $a->[0] } map { [ $flatHash{$_}, $_ ] } keys(%fla +tHash); foreach my $arrayRef (@sorted) { print "$arrayRef->[0] $arrayRef->[1]\n"; }

update: made sure of no value collisions in reverse, quoted octal key.


In reply to Re: Sorting values of multi-dimensional hashes while retaining key values by bikeNomad
in thread Sorting values of multi-dimensional hashes while retaining key values by Daddio

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.