monkini;
I'm not sure I can tell what you're asking for, but if I'm guessing correctly, your problem is that you're trying to find the subkey associated with the first key and the largest value. If so, I'm thinking this will do what you want:
#!/usr/bin/perl
use strict;
use warnings;
my %h = (
a=>{ a=>1, b=>2, c=>3, d=>4 },
b=>{ h=>5, i=>6, j=>5 },
c=>{ r=>5, s=>5, t=>5 },
e=>{ r=>5, s=>5, t=>4 },
+
);
for my $k (sort keys %h) {
my @t = kv_for_largest_v($h{$k});
print "Key $k: $t[0], $t[1]\n";
}
sub kv_for_largest_v {
my $hr = shift;
return undef unless keys %$hr;
my ($k,$v) = each %$hr;
while (my ($k2,$v2) = each %$hr) {
($k,$v) = ($k2,$v2) if $v2>$v;
}
return $k,$v;
}
This returns only a single key/value pair which you can use in your code kind of like this:
my ($maxkey, $maxmax) = kv_for_largest_v($distances{$key1};
If you want to iterate through multiples in case there are several identical maximum distances, you can return an array reference instead, and push all the "winners" to the list something like so:
sub kv_for_largest_v {
my $hr = shift;
return undef unless keys %$hr;
my ($k,$v) = each %$hr;
my @rv = ([ $k, $v ]);
while (my ($k2,$v2) = each %$hr) {
if ($v2 > $rv->[0][1]) {
# New maximum value, reset the list
$rv = ([ $k2, $v2 ]);
}
elsif ($v2 == $rv->[0][1]) {
# Another copy of the max distance, add to the list
push @rv, [ $k2, $v2 ];
}
}
return \@rv;
}
Apologies if I didn't interpret your question correctly. As I see it, the problems I had with your question are primarily that there was no clear question. The title "Separating hashed data into subsets" initially misled me into thinking you were needing some algorithmic help, so I put my thinking into "problem solving" mode. The setup with the three data structures started me thinking you were having a bookkeeping problem where you may have been having difficulty tracking your work through the algorithm, so then I switched thought modes into "analysis" mode so I could try to find where you may be losing track of the data. But about 10 minutes later, the comment "# somehow retrieve the 2nd key", triggered the thought: Oh, he found a hash value he's interested in, but doesn't have the key it came with, which appears to be the desired question.
If that *is* the desired question, then you should've pruned a little more application-specific detail from your question. I was bored this morning, though, so hopefully I found what you were looking for. If not, update your post to let us know in a bit more detail the *real* question, and I'm sure someone can help out.
As a first question to PM, it's not bad at all, but could've been a little more direct. For me, the easier questions are when someone states--in as few words as possible--the exact problem/question, and then provides all the supporting details. That way, I can switch my thought processes into the best mode for the job more easily.
...roboticus
When your only tool is a hammer, all problems look like your thumb. |