If you flatten your data structure, it would be a lot easier to access the sort key wanted. Of course this is not optimal as you need to duplicate all your data in a temporary array.
#! /usr/bin/perl
use strict;
use warnings;
my %h;
# if your data is really numerical then the apostrophes are superfluou
+s
$h{10}{20} = 5;
$h{10}{25} = 4;
$h{05}{50} = 3;
$h{20}{30} = 2;
my @temp;
for my $key1 ( keys %h ) {
for my $key2 ( keys %{ $h{$key1} } ) {
# create a 3-column table from your hash
push @temp, [ $key1, $key2, $h{$key1}{$key2} ];
}
}
# sort it by the second column numerically
for ( sort { $a->[1] <=> $b->[1] } @temp ) {
print 'key1=', $_->[0], ', key2=', $_->[1], ', value=', $_->[2], "\n
+";
}
I hope this helps.
update: a little clarification: By using the solution above you need to store every one of your key1, key2 and value at least once more, but in the terms of memory consumption this can be more than a duplicate.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.