如果我有哈希:
%hash = ("Dog",1,"Cat",2,"Mouse",3,"Fly",4);
如何提取此哈希的前X个元素。例如,如果我想要前3个元素,%newhash将包含(“Dog”,1,“Cat”,2,“Mouse”,3)。
我正在使用大哈希(约8000个键)。
答案 0 :(得分:5)
“此哈希的第一个X元素”并不意味着什么。前三个元素按数值排序?
my %hash = ( 'Dog' => 1, 'Cat' => 2, 'Mouse' => 3, 'Fly' => 4 );
my @hashkeys = sort { $hash{$a} <=> $hash{$b} } keys %hash;
splice(@hashkeys, 3);
my %newhash;
@newhash{@hashkeys} = @hash{@hashkeys};
答案 1 :(得分:0)
你可能想要使用这样的东西:
my %hash = ("Dog",1,"Cat",2,"Mouse",3,"Fly",4);
for ( (sort keys %hash)[0..2] ) {
say $hash{$_};
}
答案 2 :(得分:0)
你应该有一个数组1:
my %hash = ("Dog" => 1,"Cat"=>2,"Mouse"=>3,"Fly"=>4);
my @array;
foreach $value (sort {$hash{$a} <=> $hash{$b} }
keys %hash)
{
push(@array,{$value=>$hash{$value}});
}
#get range:
my @part=@array[0..2];
print part of result;
print $part[0]{'Cat'}."\n";