Lebowski156
Lebowski156

Reputation: 951

Perl extract range of elements from a hash

If I have a hash:

%hash = ("Dog",1,"Cat",2,"Mouse",3,"Fly",4);

How can I extract the first X elements of this hash. For example if I want the first 3 elements, %newhash would contain ("Dog",1,"Cat",2,"Mouse",3).

I'm working with large hashes (~ 8000 keys).

Upvotes: 1

Views: 1100

Answers (3)

zb'
zb'

Reputation: 8059

You should have an array 1st:

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";

Upvotes: 0

ysth
ysth

Reputation: 98398

"first X elements of this hash" doesn't mean anything. First three elements in order by numeric value?

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};

Upvotes: 5

Omid
Omid

Reputation: 170

You might want to use something like this:

my %hash = ("Dog",1,"Cat",2,"Mouse",3,"Fly",4);
for ( (sort keys %hash)[0..2] ) {
    say $hash{$_};
}

Upvotes: 0

Related Questions