哈希的哈希按指定键值排序并限制输出前5条结果的技术问题
Sort Hash of Hashes by Key Value & Get Top 5 Entries
Let's fix that while loop issue and get you the top 5 sorted entries from your hash of hashes. Your original approach has a few syntax and logic hiccups—here's how to resolve them:
Core Issues in Your Original Code
- Missing Scalar Prefix:
my limit = 5should bemy $limit = 5(Perl scalar variables require a$prefix). - While Loop Misuse:
sortreturns a list of keys, and while loops aren't built to iterate over lists directly like that. We need to sort first, then control the loop to stop after 5 entries. - Variable Typo: You referenced
$top_strategies{$keys}instead of$hoh{$keys}in your print statement.
Working Implementation (Counter-Based, Matching Your Loop Goal)
This version uses a counter to mimic the "stop after 5" behavior you wanted, with corrected syntax:
# Sample hash of hashes my %hoh = ( key1 => { aaaa => 7, bbbb => 'value1' }, key2 => { aaaa => 6, bbbb => 'value2' }, key3 => { aaaa => 5, bbbb => 'value3' }, key4 => { aaaa => 4, bbbb => 'value4' }, key5 => { aaaa => 3, bbbb => 'value5' }, key6 => { aaaa => 2, bbbb => 'value6' }, key7 => { aaaa => 1, bbbb => 'value7' }, ); my $limit = 5; my $count = 0; # Sort keys in descending order by the 'aaaa' value foreach my $key (sort { $hoh{$b}{aaaa} <=> $hoh{$a}{aaaa} } keys %hoh) { # Exit loop once we've printed 5 entries last if $count >= $limit; print "KEY: $key VALUE1: $hoh{$key}->{aaaa} VALUE2: $hoh{$key}->{bbbb}\n"; $count++; }
Even Cleaner: Array Slicing Approach
If you prefer a more concise solution, slice the sorted key list to grab just the first 5 elements directly:
my $limit = 5; my @sorted_keys = sort { $hoh{$b}{aaaa} <=> $hoh{$a}{aaaa} } keys %hoh; # Iterate over the first $limit keys (indices 0 to 4 for limit=5) foreach my $key (@sorted_keys[0 .. $limit - 1]) { print "KEY: $key VALUE1: $hoh{$key}->{aaaa} VALUE2: $hoh{$key}->{bbbb}\n"; }
Expected Output
Both implementations will print:
KEY: key1 VALUE1: 7 VALUE2: value1 KEY: key2 VALUE1: 6 VALUE2: value2 KEY: key3 VALUE1: 5 VALUE2: value3 KEY: key4 VALUE1: 4 VALUE2: value4 KEY: key5 VALUE1: 3 VALUE2: value5
内容的提问来源于stack exchange,提问作者Abdul Ahmed
相关产品推荐
相关产品推荐

