Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

of course, jettero posted already a very compact working solution, but I found the topic interesting enough to try that one too. In contrast to the solution already given, one could solve these problems per 'hash flipping'. This would trace down the hashes of hashes and at the end of the way would put the keys of the chain plus the value into an array. This array would then be a 'flipped hash representation'. This could then be handled simply by a loop:

... my @flipped_hash = reverse sort {$a->[0] <=> $b->[0] } flippout %bdry +; ...

(reverse sort - to get your desired order). This may be printed via:

... for my $k ( @flipped_hash ) { print " \$bdry{$k->[1]}{$k->[2]} = $k->[0];\n", } ...

which would print the desired output:

$bdry{1}{2} = 3; $bdry{3}{4} = 2; $bdry{2}{3} = 1;

How would such a flippout() subroutine look like? A straightforward implementation would read like:

... sub flippout { my %h = @_; my @f; while( my ($k,$v) = each %h ) { while( my ($vk,$vv) = each %$v) { push @f, [$vv, $k, $vk] } } return @f } ...

This seems to be something like an explicit version of jettero's code.

Regards

mwa


In reply to Re: sorting HoH according to value by mwah
in thread sorting HoH according to value by sovixi

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-23 06:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found